如何使用dc.js创建饼图

时间:2014-04-11 07:28:47

标签: csv d3.js dc.js

我使用Dimensional Charting javascript库dc.js制作了一个饼图,它基于d3和crossfilter。我是dc.js library.i的新手。我正在尝试使用csv file.i来了解如何按照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

1 个答案:

答案 0 :(得分:2)

根本问题在于,您所需的图表类型的数据处于错误的“形状”。您希望当前的列标题实际存在于您的数据中,以便您可以按它们进行分组。我怀疑有一种更优雅的方式来重塑你的数据,但我在下面的内容应该很容易理解。一旦这些标签是实际数据而不是元数据,剩下的就非常简单了。

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();