D3中的arc.centroid返回(NaN, NaN)

3

提醒:我在D3方面是个新手。我正在使用D3构建一个甜甜圈图表,目前一切顺利,唯独是片上的标签与片不对齐。使用下面的代码,每个片的标签都呈现在图表的中间,叠在彼此之上,因此无法阅读。我已经在我的变换属性中删除了arc.centroid,但它返回的是“NaN,NaN”而不是实际坐标,并且我无法理解它从哪里读取,以至于找不到数字。我的内半径和外半径在arc变量中定义。有什么帮助吗?

(抱歉没有jsfiddle,但我在这里从.csv获取数据)

var width = 300,
    height = 300,
    radius = Math.min(width, height) / 2;

var color = ["#f68b1f", "#39b54a", "#2772b2"];

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

var arc = d3.svg.arc()
    .innerRadius(radius - 85)
    .outerRadius(radius);

var svg = d3.select("#pieplate").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

d3.csv("data.csv", type, function(error, data) {
  var path = svg.datum(data).selectAll("path")
      .data(pie)
    .enter().append("path")
      .attr("fill", function(d, i) { return color[i]; })
      .attr("d", arc)
      .each(function(d) { this._current = d; }); // store the initial angles

  var text = svg.selectAll("text")
                        .data(data)
                        .enter()
                        .append("text")
                        .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
                        .attr("dy", ".35em")
                        .attr("text-anchor", "middle")
                        .text( function (d) { return d.taskforce1; })
                        .attr("font-family", "sans-serif")
                        .attr("font-size", "20px")
                        .attr("fill", "black");

  d3.selectAll("a")
      .on("click", switcher);

  function switcher() {
    var value = this.id;
    var j = value + 1;
    pie.value(function(d) { return d[value]; }); // change the value function
    path = path.data(pie); // compute the new angles
    path.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
    textLabels = text.text( function (d) { return d[value]; });
  }
});

function type(d) {
  d.taskforce1 = +d.taskforce1;
  d.taskforce2 = +d.taskforce2;
  d.taskforce3 = +d.taskforce3;
  return d;
}

// Store the displayed angles in _current.
// Then, interpolate from _current to the new angles.
// During the transition, _current is updated in-place by d3.interpolate.
function arcTween(a) {
  var i = d3.interpolate(this._current, a);
  this._current = i(0);
  return function(t) {
    return arc(i(t));
  };
}
1个回答

8

终于明白了。arc.centroid函数需要预先计算好的startAngle和endAngle数据,这是pie(data)的结果。因此,以下内容对我有所帮助:

var text = svg.selectAll("text")
                    .data(pie(data))

紧接着是其余的调用。请注意,您可能需要更改访问要显示的文本数据的方式。您可以随时使用以下方法进行检查

// while adding the text elements
    .text(function(d){ console.log(d); return d.data.textAttribute })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接