Reputation: 151
I'm trying to make a pie chart using multiple columns from a csv file, I can produce a pie chart but it only use the last value d.gre. What am I doing wrong?
Code is below
d3.csv("elecVotes.csv", function (data) {
var ndx = crossfilter(data);
var partysDim = ndx.dimension(function(d) { return +d.rep, +d.dem, +d.lib, +d.ind, +d.gre;})
var partys = partysDim.group();
var pie = dc.pieChart('#chart-pie');
pie
.width(180)
.height(180)
.radius(80)
.dimension(partysDim)
.group(partys)
.renderLabel(true)
.innerRadius(10)
.transitionDuration(500)
.colorAccessor(function (d, i) { return d.value; });
dc.renderAll();
});
electVotes.csv
state, rep,dem,lib,ind,gre
Alabama,1314431,725704,44211,20276,9341
New York,5655,54444,65666,2355,12225
Texas,4355,543234,12321,12331,45644
Upvotes: 1
Views: 248
Reputation: 6010
Gordon's suggestion should work, but I would also urge you to consider getting the data into a more appropriate format up front. It will make your life easier in a lot of ways and when using a lot of different tools. Specifically, you would need to transform your file to having only three columns: State, Party, and Votes. If you are maintaining this data in Excel, do it there. Or you can run this on the file you load:
var newData = []
data.forEach(function(d) {
newData.push({state: d.state, party: 'rep', votes: d.rep})
newData.push({state: d.state, party: 'dem', votes: d.dem})
newData.push({state: d.state, party: 'lib', votes: d.lib})
newData.push({state: d.state, party: 'ind', votes: d.ind})
newData.push({state: d.state, party: 'gre', votes: d.gre})
})
data = newData
Then your Crossfilter dimension and group creation will look like this:
var ndx = crossfilter(data);
var partysDim = ndx.dimension(function(d) { return d.party;})
var partys = partysDim.group().reduceSum(function(d) { return d.votes;});
Again, this is another way of handling the same problem. I think there are big payoffs from organizing your data the right way up front so I usually recommend doing that work and then keeping the Crossfilter/dc.js code nice and simple.
Upvotes: 2
Reputation: 20150
There are a couple of problems here. On the JavaScript level, the comma "operator" just evaluates both sides of the comma and returns the second. So the value of
1,2,3,4,5
is just 5
. So that explains the result you're currently getting.
The other problem is more conceptual. Crossfilter is not designed to display each column in a group. I think the main reason is that there would be no way to filter by political party, since each region or state has values for every party. You would need data at the voter level to filter by party.
Given that restriction, you definitely won't be able to filter by clicking on the pie chart. However, with a little work, you can have the pie chart display the column sums as bins of a group.
As Ethan says, maybe it's better to transform your data, but this answer shows how to produce a group which rotates the data on the fly.
Upvotes: 2