gpt4 book ai didi

javascript - 如何用饼图表示每个数据条目的值?

转载 作者:行者123 更新时间:2023-11-30 14:35:42 26 4
gpt4 key购买 nike

假设我有以下简单数据集data

ID,A,B,C,D
a,0,1,0,0
b,1,1,1,0
c,0,0,1,1

使用标准更新模式为每个数据条目创建一个圆圈非常容易:

var course = d3.selectAll(".course")
.data(data, d => d.ID);

course.enter()
.append("circle")
.attr("r", 10)
.attr("class", "course");

course.exit().remove();

现在我想用小饼图替换圆圈,使用列中的信息。饼图应该每个 1 都有一 block 。例如,b 应该用 3 block 饼图表示(一个用于 ABC)。这是我已经尝试过的:

var course = d3.selectAll(".course")
.data(data, d => d.ID);

course.enter()
.each(function (c) {
var values = d3.values(c)
.splice(2, 5);

var pie = d3.pie()(values);

var arc = d3.arc()
.innerRadius(0)
.outerRadius(10);

d3.select(this)
.append("path")
.attr("d", arc(pie));
}

控制台中没有错误,但也没有饼图……不过,pie 中计算的 Angular 看起来不错。我做错了什么?我发现了Pie Multiples ,但我无法理解它。

最佳答案

我对 Pie Multiples block 进行了快速但非常肮脏的更新展示它是如何完成的。这有帮助吗?

https://codepen.io/anon/pen/ELMgaP

var data = [{
ID: 'a',
A: 2,
B: 1,
C: 1
},
{
ID: 'b',
A: 1,
B: 1,
C: 7
},
];

// Define the margin, radius, and color scale. The color scale will be
// assigned by index.
var m = 10,
r = 100,
z = d3.scaleOrdinal(d3.schemeCategory10);

// Insert an svg element (with margin) for each row in our dataset. A child g
// element translates the origin to the pie center.
var svg = d3.select("body").selectAll("svg")
.data(data, d => d.ID)
.enter().append("svg")
.attr("width", (r + m) * 2)
.attr("height", (r + m) * 2)
.append("g")
.attr("transform", "translate(" + (r + m) + "," + (r + m) + ")");

// The data for each svg element is a row of numbers (an array). We pass that to
// d3.pie to compute the angles for each arc. These start and end angles
// are passed to d3.arc to draw arcs!
svg.selectAll("path")
.data((d, i) => d3.pie()(d3.values(data[i]).splice(1, 5)))
.enter().append("path")
.attr("d", d => d3.arc().innerRadius(r / 2).outerRadius(r)(d))
.style("fill", function(d, i) {
return z(i);
})
.style('stroke', 'black');
<script src="https://d3js.org/d3.v4.min.js"></script>

我的猜测是您的代码也非常接近工作,但是没有看到所有变量的值我不确定这个小错误是什么(尽管我很确定它是一个小错误)。

关于javascript - 如何用饼图表示每个数据条目的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50454279/

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