javascript D3 中的饼图(甜甜圈)图段顺序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17169504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:21:19  来源:igfitidea点击:

Pie (donut) chart segment order in D3

javascriptd3.jspie-chartdonut-chart

提问by Kerplunk

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.

我有一个使用 d3 构建的甜甜圈图,带有一个 jQuery 滑块,允许用户在不同的数据点之间进行选择。该图表为数据值之间的过渡设置了动画,一切正常。

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/

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

回答by ckersch

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

d3 自动按饼图的值排序。幸运的是,禁用排序很容易,只需使用函数sort(null)上的donut方法,即:

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

Here's a fiddle.

这是一个小提琴

回答by L.Youl

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

在 d3 V4 中,这也是有效的语法(没有.layout):

d3.pie()
  .value(function(d) { return d.value; })
  .sort(null)