javascript - dc.js - Selecting Columns in csv to Render Chart -
so assume have .csv formatted this:
agegroup state gender score1 bin1 score2 bin2 18-25 tx f .15 1 .20 3 18-25 fl f .34 4 .11 7 65+ ca m .72 3 .33 9 46-54 tx m .90 6 .08 1 46-54 tx f .15 1 .11 7
right now, can create 2 bar charts columns, bin1 , bin2. have display sum score1 , score2.
however, add more scores , bins, don't want create more , more bar charts , displays each column added. if new csv looks this:
agegroup state gender score1 bin1 score2 bin2 score3 bin3 score4 bin4 18-25 tx f .15 1 .20 3 .51 2 .23 6 18-25 fl f .34 4 .11 7 .79 1 .64 4 65+ ca m .72 3 .33 9 .84 7 .55 3 46-54 tx m .90 6 .08 1 .15 2 .47 5 46-54 tx f .15 1 .11 7 .76 8 .09 8
is there way can create drop-down or tell dc.js columns (in case, bin1 through bin4) create charts off of , have display reactive display correct sums?
you can update group on chart , render it.
var groups = { bin1: dim.group().reducesum(function(d) { return d.bin1; }), bin2: dim.group().reducesum(function(d) { return d.bin2; }) }; var chart = dc.barchart("#chart") .width(400) .height(200) .x(d3.scale.linear().domain([1, 4])) .dimension(dim) .group(groups.bin1); chart.render(); function changebin (binnum) { chart.group(groups[binnum]); chart.render(); }
and working example using 2 buttons:
var data = [{ x: 1, bin1: 90, bin2: 10 }, { x: 2, bin1: 20, bin2: 20 }, { x: 3, bin1: 50, bin2: 30 }, { x: 4, bin1: 100, bin2: 40 }]; var cf = crossfilter(data); var dim = cf.dimension(function(d) { return d.x; }); var groups = { bin1: dim.group().reducesum(function(d) { return d.bin1; }), bin2: dim.group().reducesum(function(d) { return d.bin2; }) }; var chart = dc.barchart("#chart") .width(400) .height(200) .x(d3.scale.linear().domain([1, 4])) .dimension(dim) .group(groups.bin1); chart.render(); function changebin (binnum) { chart.group(groups[binnum]); chart.render(); }
<link href="https://cdnjs.cloudflare.com/ajax/libs/dc/1.7.3/dc.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.2.0/d3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/crossfilter/1.3.11/crossfilter.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/dc/1.7.3/dc.js"></script> <div id="chart"></div> <button onclick="changebin('bin1');">bin 1</button> <button onclick="changebin('bin2');">bin 2</button>
Comments
Post a Comment