如何使用 D3.js 实现这个圆环图?有人请帮助我。
我试过下面的代码,但我在设计中遇到了 Angular 半径和灰色圆弧的问题:
Javascript:
var dataset = {
apples: [53245, 28479, 19697, 24037, 40245],
};
var width = 460,
height = 300,
radius = Math.min(width, height) / 2;
var color = d3.scale.category20();
var pie = d3.layout.pie()
.sort(null);
var arc = d3.svg.arc()
.innerRadius(radius - 100)
.outerRadius(radius - 50);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var path = svg.selectAll("path")
.data(pie(dataset.apples))
.enter().append("path")
.attr("fill", function(d, i) { return color(i); })
.attr("d", arc);
CSS:
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
margin: auto;
position: relative;
width: 960px;
}
text {
font: 10px sans-serif;
}
jsfiddle.net/gregfedorov/qh9x5/9
最佳答案
你可以这样做:
首先定义数据:
var dataset = [{
color: "red",
value: 11
}, {
color: "blue",
value: 20
}, {
color: "yellow",
value: 12
}, {
color: "transparent",//transparent for the gray part
value: 22
}];
为灰色部分定义圆弧:
var arc1 = d3.svg.arc()
.innerRadius(radius - 18)
.outerRadius(radius - 13);
为其他颜色的 donut 部分定义圆弧:
var arc = d3.svg.arc()
.innerRadius(radius - 20)
.outerRadius(radius - 10);
现在像这样在背景中制作灰色 donut :
var path = svg.selectAll(".background")
.data(pie([{
color: "gray",
value: 1
}]))
.enter().append("path")
.attr("class", "background")
.attr("fill", function(d, i) {
return d.data.color;
})
.attr("d", arc1);
现在制作彩色 donut 部分(数据集中会有一个颜色为透明
的部分,它将显示后面的灰色 donut )想法是将一个 donut chart 叠加在另一个上面。
var path = svg.selectAll(".foreground")
.data(pie(dataset))
.enter().append("path")
.attr("class", "foreground")
.attr("fill", function(d, i) {
return d.data.color;
})
.attr("d", arc);
工作示例 here
关于javascript - 如何实现D3圆环图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35953877/