6

I'm using a d3 donut chart for a project and I'm having issues centering the text inside the donut. I found a piece of code that I have modifying, but frankly I don't understand it much.

I have added the text in the center, but it's not quite centered. Is there anyone that could help me center it? I tried adding 'margin-top' to bring it down but that doesn't work, nor do a lot of css things I tried.

Here's the specific part that attaches the text:

 svg.append("text")
       .attr({
         "text-anchor": "middle",
       }).style({'fill': 'red', 'font-size': '18px'}).text(calories);
};

Codepen: http://codepen.io/anon/pen/xwwBBm

socialight
  • 487
  • 1
  • 5
  • 18
  • Try this http://stackoverflow.com/questions/28097184/adding-text-to-the-center-of-a-d3-donut-graph – Madalina Taina Sep 12 '15 at 17:03
  • that's exactly the question I used to help me add the middle text in the first place. The result is what you see in my codepen. It's not centered. – socialight Sep 12 '15 at 17:04
  • I understand. What I see is a vertical alignment problem. I'm not really a svg expert, but here is a closer example for this: http://stackoverflow.com/questions/19622421/d3-js-vertical-alignment-of-text-in-a-donut-chart – Madalina Taina Sep 12 '15 at 17:19
  • Try add for the text this too: transform-origin: 0px 0px 0px; – Madalina Taina Sep 12 '15 at 17:37

1 Answers1

7

You may have noticed that two labels outside the circle are vertically centered, but the one in the middle is not.

It is missing following line:

 .attr('dy', '0.35em')

This is the new codepen.

enter image description here

I will leave to you to discover why is that line magical.

VividD
  • 10,456
  • 6
  • 64
  • 111