警告:我是D3的新手。我正在使用D3构建一个甜甜圈图表,到目前为止一切都很好,除了切片上的标签没有与切片对齐。使用下面的代码,每个切片的标签呈现在图表的中间,堆叠在彼此的顶部,因此它们是不可读的。我在transform属性中删除了arc.centroid,但它返回的是"NaN,NaN“而不是实际的坐标,我不明白它是从哪里读取的,它没有找到一个数字。我的innerRadius和outerRadius是在arc变量中定义的。有什么帮助吗?
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));
};
}发布于 2014-07-14 17:10:04
终于明白了。arc.centroid函数需要预先计算好的startAngle和endAngle的数据,这是pie(数据)的结果。因此,以下内容对我很有帮助:
var text = svg.selectAll("text")
.data(pie(data))接下来是其他的电话。请注意,您可能必须更改访问要显示的文本数据的方式。您可以随时使用以下命令进行检查
// while adding the text elements
.text(function(d){ console.log(d); return d.data.textAttribute })https://stackoverflow.com/questions/24170899
复制相似问题