Cleaning up d3 code and removing duplication