因此假设我有一个格式如下的 .csv:
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
现在,我可以为 bin1 和 bin2 列创建两个条形图。我还有一个显示器可以对分数 1 和分数 2 求和。
但是,当我添加更多分数和数据箱时,我不想为添加的每一列创建越来越多的条形图和显示。因此,如果新的 csv 看起来像这样:
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
有什么方法可以创建一个下拉列表或其他东西来告诉 dc.js 哪些列(在本例中为 bin1 到 bin4)创建图表并让显示 react 显示正确的总和?
最佳答案
您可以更新图表上的组并进行渲染。
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();
}
使用两个按钮的工作示例:
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>
关于javascript - dc.js - 选择 csv 中的列来渲染图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30925312/