Skip to content Skip to sidebar Skip to footer

D3js Switching Between Multiple Charts

While learning on my own and being brand new to D3.js, I'm trying to create multiple pie charts with different categories switched by custom buttons. I created an individual pie ch

Solution 1:

There were several issues with your code and I had to make several changes.

If I understand correctly the main idea for you was to redraw the pie charts depending on what data the user clicks on i.e. "Gender" "Age" or "Race".

  1. The data for each of these is very different, i.e. different object key-value pairs. I made all the count keys the same (in the age dataset they were Count).

  2. Since the data is very different the examples you show where the data gets updated may not apply here as the data does not transform in this case. Instead the approach I took was to just clear the div and redraw a pie chart. So the first thing it does is to clear the chart area and then begins drawing. This significantly reduces the amount of code needed (your main.js = >300 lines, whereas mine 138 lines)

  3. I improved the tooltip as your data keys change so this needs to be accounted for in the tooltip.

  4. I moved your data to a separate js file to not clutter the main.js. I just make sure to call that before the main.js in the index.html file.

  5. I updated the function color(d) function to pick the colors from an array of objects based on the data keys. You can expand the array to your needs. If you want to use colors within a range you can use var color = d3.scale.category20(); and call the color using the index of the data like .attr("fill", function (d, i) { return color(i);}) as shown in this example http://bl.ocks.org/j0hnsmith/5591116

Here is a working block https://bl.ocks.org/akulmehta/923f277f8a10d0c35b77f6e3a84929bf/

Note that since a lot of data points for age and race are 0, the animation stutters a bit. Also note that your labels are overlapping when you have arcs very close to each other. Hence I would suggest removing the labels.

Post a Comment for "D3js Switching Between Multiple Charts"