问题描述
我是新的d3.js和我试图制作一个饼图与它
我只有一个问题:我不能得到我的标签外面我的弧...
标签使用arc.centroid定位
arcs.append(svg:text)
.attr (transform,function(d){
returntranslate(+ arc.centroid(d)+);
})
.attr middle)
谁能帮我解决这个问题?
请参阅fiddle:
基本上,调用 arc.centroid(d)
会返回一个 [x,y]
数组,你可以使用毕达哥拉斯定理计算斜边,它是从饼图中心到圆弧中心线的长度,然后可以使用 x / h * desiredLabelRadius
和 y / h * desiredLabelRadius
为您的标签锚点计算所需的 x,y
:
.attr(transform,function(d){
var c = arc.centroid(d),
x = c [0]
y = c [1],
//斜边的pythagorean定理
h = Math.sqrt(x * x + y * y);
returntranslate(+(x / h * labelr)+','+
(y / h * labelr)+)
})
这里唯一的缺点是 :middle
不是一个很好的选择 - 你最好设置 text-anchor
基于我们的饼的一面, re on:
.attr(text-anchor,function(d){
//中心?
return(d.endAngle + d.startAngle)/ 2> Math.PI?
end:start;
})
I'm new to d3.js and I"m trying to make a Pie-chart with it.I have only one problem: I can't get my labels outside my arcs...The labels are positioned with arc.centroid
arcs.append("svg:text")
.attr("transform", function(d) {
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle")
Who can help me with this?
I can solve that problem - with trigonometry :).
See fiddle: http://jsfiddle.net/nrabinowitz/GQDUS/
Basically, calling arc.centroid(d)
returns an [x,y]
array. You can use the Pythagorean Theorem to calculate the hypotenuse, which is the length of the line from the center of the pie to the arc centroid. Then you can use the calculations x/h * desiredLabelRadius
and y/h * desiredLabelRadius
to calculate the desired x,y
for your label anchor:
.attr("transform", function(d) {
var c = arc.centroid(d),
x = c[0],
y = c[1],
// pythagorean theorem for hypotenuse
h = Math.sqrt(x*x + y*y);
return "translate(" + (x/h * labelr) + ',' +
(y/h * labelr) + ")";
})
The only downside here is that text-anchor: middle
isn't a great choice anymore - you'd be better off setting the text-anchor
based on which side of the pie we're on:
.attr("text-anchor", function(d) {
// are we past the center?
return (d.endAngle + d.startAngle)/2 > Math.PI ?
"end" : "start";
})
这篇关于标签外圆弧(饼图)d3.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!