gpt4 book ai didi

javascript - 如何使用 D3 和 JS 字典制作多个饼图?

转载 作者:行者123 更新时间:2023-11-30 12:55:16 30 4
gpt4 key购买 nike

我正在尝试改编 Mike Bostock 的 example 中的代码制作多个饼图。它非常简洁,但我很难理解一段基本代码:

// Define the data as a two-dimensional array of numbers. If you had other
// data to associate with each number, replace each number with an object, e.g.,
// `{key: "value"}`.
var data = [
[11975, 5871, 8916, 2868],
[ 1951, 10048, 2060, 6171],
[ 8010, 16145, 8090, 8045],
[ 1013, 990, 940, 6907]
];

{key: "value"} 的例子是什么?我试过了

[{key1: 100}, {key2: 200}]

[{key1: 100, key2: 200}]

[{'key1': 100, 'key2': 200}]以及其他一些排列。

我的目标是使用 json 对象而不是像这样的数据结构,但我想更好地理解如何构建正确的数据结构。

要生成图表(通过要点),使用以下代码:

var m = 10,
r = 100,
z = d3.scale.category20c();

var svg = d3.select(".sentiment-pie-chart-1").selectAll("svg")
.data(data)
.enter().append("svg:svg")
.attr("width", (r + m) * 2)
.attr("height", (r + m) * 2)
.append("svg:g")
.attr("transform", "translate(" + (r + m) + "," + (r + m) + ")");

svg.selectAll("path")
.data(d3.layout.pie())
.enter().append("svg:path")
.attr("d", d3.svg.arc()
.innerRadius(r / 2)
.outerRadius(r))
.style("fill", function(d, i) { return z(i); });

最佳答案

您可以使用任意结构(包括您列出的结构),只要您还替换饼图布局从该结构中提取值的方式。这意味着您可能需要一致的键名。例如对于数据结构

[{key1: 100}, {key1: 200}]

您需要使用 .value() function 定义饼图布局如下-- 我想这是你的问题。

svg.selectAll("path")
.data(d3.layout.pie().value(function(d) { return d.key1; })
// etc

这将获取每个数组中的每个元素(请注意,这里有 2 个嵌套的对象数组)并获取成员 .key1 以计算饼图分数。

关于javascript - 如何使用 D3 和 JS 字典制作多个饼图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19388219/

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