D3.js - 带有多个环的甜甜圈图表

CLi*_*own 11 javascript d3.js

以下示例显示了D3.js中的圆环图,是否可以向图表添加多个环?

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);
Run Code Online (Sandbox Code Playgroud)

示例:http://jsfiddle.net/gregfedorov/Qh9X5/9/

所以在我的数据集中我想要如下内容:

var dataset = {
  apples: [53245, 28479, 19697, 24037, 40245],
  oranges: [53245, 28479, 19697, 24037, 40245],
  lemons: [53245, 28479, 19697, 24037, 40245],
  pears: [53245, 28479, 19697, 24037, 40245],
  pineapples: [53245, 28479, 19697, 24037, 40245],
};
Run Code Online (Sandbox Code Playgroud)

我想要的是在同一个中心点共有5个环,这是可能的,有没有人有一个例子?

Lar*_*off 17

是的,你可以很容易地做到这一点.关键是使用嵌套选择.也就是说,您传入列表的顶级列表并为每个列表创建容器元素.然后执行嵌套选择并绘制实际元素.在这种特殊情况下,您还需要调整弧的半径,使它们不重叠.

var gs = svg.selectAll("g").data(d3.values(dataset)).enter().append("g");
var path = gs.selectAll("path")
  .data(function(d) { return pie(d); })
.enter().append("path")
  .attr("fill", function(d, i) { return color(i); })
  .attr("d", function(d, i, j) {
    return arc.innerRadius(10+cwidth*j).outerRadius(cwidth*(j+1))(d);
  });
Run Code Online (Sandbox Code Playgroud)

在这里更新了jsfiddle .