控制d3js饼图动画并在饼图中放置标签

时间:2013-08-24 15:30:04

标签: javascript svg d3.js

我是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) 但我得到了“意外的值转换(NaN,NaN)解析变换属性。”Firefox中的警告和标签相互重叠。

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

1 个答案:

答案 0 :(得分:3)

我终于明白了。

在整个动画中维护扇区顺序。

你认为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 内部外部半径,最重要的是我的问题,开始结束角度。我的代码中缺少后者。获取这些值非常简单,使用我们的数据集调用上面的饼图布局,然后执行转换请注意,如果您使用d3创建了SVG并且已经提供了包含在.data()结构中的数据,则无需再次调用.pie()。也就是说,您没有从页面中选择任何现有的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 ,而不是转换/翻译

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