Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

javascript - D3.js - Donut charts with multiple rings

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Updated jsfiddle here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...