Pie (donut) chart segment order in D3
Asked Answered
P

2

15

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);
  };
}
Purine answered 18/6, 2013 at 12:59 Comment(0)
B
41

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.

Beggar answered 18/6, 2013 at 14:7 Comment(3)
That works great! Thank you very much. Was this documented somewhere that I should have found it? I did look (honest) :)Purine
It's in the docs for pie layout, under pie.sort. Url is github.com/mbostock/d3/wiki/Pie-Layout.Beggar
I found the value stuff a bit diverting in this answer - as ckersch says it's that last bit, the .sort(null) that is turning off the sorting.Composer
H
4

In d3 V4 this is also valid syntax (without the .layout):

d3.pie()
  .value(function(d) { return d.value; })
  .sort(null)
Hartwig answered 13/9, 2019 at 9:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.