最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding text to the center of a D3 Donut Graph - Stack Overflow

programmeradmin3浏览0评论

Fiddle

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 + ")";
})

Fiddle

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 + ")";
})
Share Improve this question asked Jan 22, 2015 at 19:34 BrianBrian 1551 gold badge2 silver badges10 bronze badges 1
  • I would use a different library for charts, d3js would make you write more. Check this stackoverflow.com/a/17293220/1197775. Note how objects already have properties to represent things that you are interested when working with graphs: center – sites Commented Jan 22, 2015 at 19:58
Add a comment  | 

1 Answer 1

Reset to default 21

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.

发布评论

评论列表(0)

  1. 暂无评论