我想获取“国家/地区”列的总和值,我编写了这段代码,但没有看到总和值
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
</head>
<body>
<canvas id="barchart" width="100%" height="40%"></canvas>
<canvas id="piechart" width="100%" height="40%"></canvas>
<script>
d3.csv("brokenstone copy.csv", function(csv_data) {
var nested_data = d3.nest()
.key(function(d) {return d.Country})
.rollup(function(s){
return d3.sum(s,function(d) {
return d.Amount;
})
})
.entries([csv_data]);
console.log(nested_data);
return csv_data;
}).then(makechart);
function colorGen() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
const transparent = '0.6';
return "rgb(" + r + "," + g + "," + b + "," + transparent + ")";
}
function makechart(csv_data){
// console.log(csv_data);
var prd = [],
amt = [],
frac = [];
csv_data.forEach(element => {
prd.push(element.Country);
amt.push(element.Amount);
});
var alldata = {};
alldata['datasets'] = [];
alldata['labels'] = ['Amount, тн'];
csv_data.forEach(element => {
var sample = {};
sample['data'] = [element.Amount];
sample['backgroundColor'] = colorGen();
sample['label'] = element.Country;
alldata['datasets'].push(sample);
});
var barchart = new Chart('barchart', {
type: 'bar',
data: alldata,
options: {
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
fontSize: 16,
text: 'Country by amount, тн'
}
}
});
</script>
</body>
</html>
我的数据:
Year,Month,Country,Amount
2019,2,Germany,70
2019,3,Germany,65
2019,1,Germany,61
2019,1,Germany,39
2019,1,Italy,11966
2019,5,Italy,2489
2019,1,Italy,2262
2019,6,Germany,139
2019,4,Germany,111
2019,5,Germany,69
2019,6,Germany,67
答案 0 :(得分:1)
这里的问题非常简单:您所有的nested_data
嵌套都在 row 函数内部。
将为CSV中的每一行调用行函数。正如API所说,
如果指定了行转换函数,则会为每一行调用指定的函数,并传递代表当前行的对象(d),第一个非标题行的索引(i)从零开始,并且列名称数组。
但是,这对于嵌套根本不起作用。 nest()
方法需要获取所有数据数组。
话虽如此,只需将嵌套移动到then
内部即可。如您所见,您的嵌套本身没有问题:
const csv = `Year,Month,Country,Amount
2019,2,Germany,70 2019,3,Germany,65
2019,1,Germany,61
2019,1,Germany,39
2019,1,Italy,11966
2019,5,Italy,2489
2019,1,Italy,2262
2019,6,Germany,139
2019,4,Germany,111
2019,5,Germany,69
2019,6,Germany,67`;
const data = d3.csvParse(csv, d3.autoType);
const nested_data = d3.nest()
.key(function(d) {
return d.Country
})
.rollup(function(s) {
return d3.sum(s, function(d) {
return d.Amount;
})
})
.entries(data);
console.log(nested_data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>