【问题标题】:Controlling d3js pie animations and place labels inside pie控制 d3js 饼图动画并在饼图中放置标签
【发布时间】:2013-08-27 12:41:00
【问题描述】:

我完全不熟悉 D3 和部分 SVG,所以我有几个基本问​​题。 首先,我有问题的代码可以在http://dotnetcarpenter.github.io/d3-test/ 查看,我使用Simple Pie Chart example with D3.jsPie Chart Update, II 作为示例来开始运行。

如您所见,当低路径值切换到较高值时,动画最终会倾斜。这显然不是我想要的。我想我的计算顺序是错误的,但我不知道该怎么做。我正在使用上一个示例中的代码:

function change() {
  //...
  path.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
}
// where arcTween is
function arcTween(a) {
  var i = d3.interpolate(this._current, a);
  this._current = i(0);
  return function(t) {
    return arc(i(t));
  };
}

另一个问题是在扇区上放置标签。我已将更新内容放在更改函数中,并且能够读出并仅在值介于 0 和 100 之间时才呈现它们。但是我不能以任何方式放置它们。看第一个例子,我想我可以做这样的事情:

text.data(data)
    .text(setText)
    .attr("transform", function (d) {
      // we have to make sure to set these before calling arc.centroid
      d.innerRadius = 0;
      d.outerRadius = radius;
      return "translate(" + arc.centroid(d) + ")";
    })
    .attr("text-anchor", "middle") //center the text on it's origin

其中 text 是 d3 选择,arc 是:d3.svg.arc().outerRadius(radius) 但我在 Firefox 中收到“Unexpected value translate(NaN,NaN) parsing transform attribute.”警告,并且标签彼此重叠。

感谢任何帮助和提示。谢谢!

【问题讨论】:

    标签: javascript svg d3.js


    【解决方案1】:

    我终于明白了。

    在整个动画中保持扇区顺序。

    如果您认为object contancy 与它有关,那是可以原谅的。我做到了。但事实证明它比这简单得多。

    默认情况下,每个饼图都按值排序。如果您不想按值排序,但例如按数据列表顺序,您只需禁用排序即可。

    var pie = d3.layout.pie() // get a pie object structure
                .value(function(d) { // define how to get your data value
                    return d.value;  // (based on your data set)
                })
                .sort(null); // disable sort-by-value
    

    根据图表定位标签

    基本上,您需要根据图表或图形的类型以及您尝试将它们连接到的类型来计算标签位置。就我而言,它是一个饼图。所以如果我想让 d3 帮助计算,我需要告诉centroid 外半径,最重要的是我的问题,开始端角。我的代码中缺少后者。获取这些值就像使用我们的数据集调用上面的饼图布局然后执行 transform 一样简单。 请注意,如果您使用 d3 创建了 SVG 并且已经提供了包装在 .pie() 结构中的数据,则不必再次调用 .data()。也就是说,您没有从页面中选择任何现有的 SVG。

    var svg =  d3.select("svg")
                 // do stuff with your svg
    var pie = d3.layout.pie()
                 // set stuff on your layout
    var text = svg.selectAll("text")
                  .data(pie(dataset)) // where dataset contains your data
                  .attr("transform", function(d) {
                                         return "translate(" + arc.centroid(d) + ")";
                                     });
    

    一路走来,我必须感谢 Philip Pedruco helping me

    奖金信息

    如果您想定位您的 SVG 跨浏览器,请使用 viewBox,而不是 transform/translate

    // move pie to center
    d3.select("svg").attr("viewBox", -radius + ","+ -radius +"," + size + "," + size) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-15
      • 1970-01-01
      • 2014-10-09
      相关资源
      最近更新 更多