D3.js - 多环图表 [英] D3.js - Donut charts with multiple rings

查看:126
本文介绍了D3.js - 多环图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The following example shows a donut chart in D3.js, is it possible to add more than one ring to the chart?

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

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

所以在我的数据集中,我想要像下面这样:

So in my data set I want something like the following:

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],
};

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

What I want is to have 5 rings in total all around the same central point, is this possible and does anyone have an example?

推荐答案

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

Yes, you can do this quite easily. The key is to use nested selections. That is, you pass in your top level list of lists and create a container element for each list. Then you do the nested selection and draw the actual elements. In this particular case, you also need to adjust the radii of the arcs so that they don't overlap.

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

更新jsfiddle 此处

Updated jsfiddle here.

这篇关于D3.js - 多环图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆