D3js Switching Between Multiple Charts
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".
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 wereCount
).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)
I improved the tooltip as your data keys change so this needs to be accounted for in the tooltip.
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.
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 usevar 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"