gpt4 book ai didi

csv - 如何使用 dc.js 创建饼图

转载 作者:行者123 更新时间:2023-12-02 01:50:30 30 4
gpt4 key购买 nike

我正在使用基于 d3 和 crossfilter 的 Dimensional Charting javascript 库 dc.js 制作饼图。我是 dc.js 库的新手。我正在尝试使用 csv 文件显示饼图。我无法理解如何按照 csv 格式创建饼图。

我的 csv 列格式是

 Age_19_Under   Age_19_64   Age_65_84   Age_85_and_Over
26.9 62.3 9.8 0.9
23.5 60.3 14.5 1.8
24.3 62.5 11.6 1.6
24.6 63.3 10.9 1.2
24.5 62.1 12.1 1.3
24.7 63.2 10 2.2
25.6 58.5 13.6 2.4
24.1 61.6 12.7 1.5
24.8 59.5 13.5 2.2

我想绘制下图的饼图:

enter image description here

最佳答案

根本问题是您的数据对于您想要的图表类型来说是错误的“形状”。您希望当前的列标题实际包含在您的数据中,以便您可以按它们分组。我怀疑有一种更优雅的方法来 reshape 您的数据,但我在下面给出的内容应该很容易理解。一旦这些标签是实际数据而不是元数据,剩下的就非常简单了。

var experiments = [
{ Age_19_Under: 26.9, Age_19_64: 62.3, Age_65_84: 9.8, Age_85_and_Over: 0.9 },
{ Age_19_Under: 23.5, Age_19_64: 60.3, Age_65_84: 14.5, Age_85_and_Over: 1.8 },
{ Age_19_Under: 24.3, Age_19_64: 62.5, Age_65_84: 11.6, Age_85_and_Over: 1.6 },
{ Age_19_Under: 24.6, Age_19_64: 63.3, Age_65_84: 10.9, Age_85_and_Over: 1.2 },
{ Age_19_Under: 24.5, Age_19_64: 62.1, Age_65_84: 12.1, Age_85_and_Over: 1.3 },
{ Age_19_Under: 24.7, Age_19_64: 63.2, Age_65_84: 10.0, Age_85_and_Over: 2.2 },
{ Age_19_Under: 25.6, Age_19_64: 58.5, Age_65_84: 13.6, Age_85_and_Over: 2.4 },
{ Age_19_Under: 24.1, Age_19_64: 61.6, Age_65_84: 12.7, Age_85_and_Over: 1.5 },
{ Age_19_Under: 24.8, Age_19_64: 59.5, Age_65_84: 13.5, Age_85_and_Over: 2.2 },
];

// Reshape the data
var categoryList = new Array();
experiments.forEach(function (exp) {
categoryList.push({ Category: "Age_19_Under", Value: exp.Age_19_Under });
categoryList.push({ Category: "Age_19_64", Value: exp.Age_19_64 });
categoryList.push({ Category: "Age_65_84", Value: exp.Age_65_84 });
categoryList.push({ Category: "Age_85_and_Over", Value: exp.Age_85_and_Over });
});

// Setup crossfilter
var ndx = crossfilter(categoryList);
var categoryDim = ndx.dimension(function (d) { return d.Category; });
var valueSumGroup = categoryDim.group().reduceSum(function (d) { return d.Value; });

// Create the chart
var pieChart = dc.pieChart("#chartid");
pieChart
.dimension(categoryDim)
.group(valueSumGroup)
.radius(100)
;

dc.renderAll();

关于csv - 如何使用 dc.js 创建饼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23006194/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com