将文本添加到D3圆环图的中心 [英] Adding text to the center of a D3 Donut Graph
问题描述
我试图基本上在使用D3的圆环图的中心。我能够使用现有的代码,我发现和操纵它,所以图形网格的所有切片在中间出现像有一个标签,但我认为这将是一个更好的主意,只是为了弄清楚如何使它成为一个更永久的家在中心。我对JS和D3非常新。
谢谢
这是目前正在伪造中心标签的程式码。
svg.selectAll(text) .data(pie(data))。enter()
.append(text)
.attr(class,label1)
.attr (d){
var dist = radius-120;
var winkel =(d.startAngle + d.endAngle)/ 2;
var x = dist * Math.sin(winkel) 4;
var y = -dist * Math.cos(winkel)-4;
returntranslate(+ x +,+ y +);
})
。由于您已经以饼图为中心:
var svg = d3.select(#svgContent)。append )
.attr(width,width)
.attr(height,height)
.append(g)
.attr translate(+ width / 2 +,+ height / 2 +));
您可以按如下方式添加文本:
svg.append(text)
.attr(text-anchor,middle)
.text($+ totalValue) ;
请注意,由于您只添加一个< text>
,你不需要绑定任何数据,并且可以直接传递 .text(...)
一个值而不是一个函数。 p>
I am trying to insert basically a label to the center of a donut graph using D3. I was able to work with an existing code I found and manipulate it so all the slices of the graph mesh in the middle to appear like there is a label there, but I think it'd be a better idea just to figure out how to make it a more permanent home in the center. I am very new to JS and D3.
Any help is grealty appreciated.
Thank you
This is currently the code that is falsifying a label being in the center.
svg.selectAll("text").data(pie(data)).enter()
.append("text")
.attr("class","label1")
.attr("transform", function(d) {
var dist=radius-120;
var winkel=(d.startAngle+d.endAngle)/2;
var x=dist*Math.sin(winkel)-4;
var y=-dist*Math.cos(winkel)-4;
return "translate(" + x + "," + y + ")";
})
You can simplify your code quite a bit. Since you are already centering the pie chart:
var svg = d3.select("#svgContent").append("svg")
.attr("width",width)
.attr("height",height)
.append("g")
.attr("transform","translate("+width/2+","+height/2+")");
You can just add the text as follows:
svg.append("text")
.attr("text-anchor", "middle")
.text("$" + totalValue);
Note that since you are only adding one <text>
, you don't need to bind any data to it, and can pass .text(...)
a value directly instead of a function.
这篇关于将文本添加到D3圆环图的中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!