Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pie (donut) chart segment order in D3

I have a donut chart built using d3 with a jQuery slider that allows a user to select between different data-points. The chart animates the transition between data values and all is well.

The problem: The segments always render in anti-clockwise size order (from largest to smallest). This means that segments switch their position around the chart depending on their size.

This behaviour is confusing for users, but unfortunately I can't work out how to change it. I would like the segments to stay in their initial position.

Working js-fiddle: http://jsfiddle.net/kerplunk/Q3dhh/

I believe the problem must lie in the function which does the actual tweening:

// Interpolate the arcs in data space.
function pieTween(d, i) {
  var s0;
  var e0;
  if(oldPieData[i]){
    s0 = oldPieData[i].startAngle;
    e0 = oldPieData[i].endAngle;
  } else if (!(oldPieData[i]) && oldPieData[i-1]) {
    s0 = oldPieData[i-1].endAngle;
    e0 = oldPieData[i-1].endAngle;
  } else if(!(oldPieData[i-1]) && oldPieData.length > 0){
    s0 = oldPieData[oldPieData.length-1].endAngle;
    e0 = oldPieData[oldPieData.length-1].endAngle;
  } else {
    s0 = 0;
    e0 = 0;
  }
  var i = d3.interpolate({startAngle: s0, endAngle: e0}, {startAngle: d.startAngle, endAngle: d.endAngle});
  return function(t) {
    var b = i(t);
    return arc(b);
  };
}
like image 285
Kerplunk Avatar asked Jun 18 '13 12:06

Kerplunk


People also ask

What is D3 layout?

D3 layout methods are helpful for implementing a range of visualizations, such as stacked bar charts, treemaps, or node-link diagrams, that require a more advanced positioning of visual marks. For example, to lay out elements relative to each other instead of positioning them at given [x,y] coordinates.

Is pie chart and donut chart different in usage?

A donut chart is basically a pie chart with its center removed. Instead of slices, you use arc segments to display individual dimensions. This type of chart can help you compare individual categories or dimensions to the larger whole, just like a pie chart, but with a couple of advantages.

What is the command to invoke pie in D3?

js pie() Function. The d3. pie() is used to construct a pie generator that has its default settings. This pie generator takes an array of data and then returns an array of objects that contains details about each arc angle.


1 Answers

d3 automatically sorts by value for pie charts. Luckily, disabling sorting is quite easy, just use the sort(null) method on thedonut function, i.e.:

var donut = d3.layout.pie().value(function(d){
    return d.itemValue;
}).sort(null);

Here's a fiddle.

like image 103
ckersch Avatar answered Oct 16 '22 13:10

ckersch