I would like to place a title in the center of a pie/donut chart in HighCharts.
I don't see anything in the chart options that would directly enable this, so I'm thinking it requires using the Highcharts SVG renderer -- chart.renderer.text('My Text', x, y)
.
I have that set up but I can't get the text to be centered inside the pie. Percentages don't seem to be accepted for x and y values. Is there a programmatic way to get it centered inside the plot, and to survive container resizing?
Update: Setting x and y to 50% works fine to center a circle (using renderer.circle(x, y, radius)
)—but not to center text (using renderer.text(text, x, y)
).
See result here: http://jsfiddle.net/supertrue/e2qpa/
Use this code to center chart title vertically:
title: { verticalAlign: 'middle', floating: true }
Example
Since version 2.1 The floating property can be omitted as the documentation states it is implied by the presence of the verticalAlign property
When a value is given, the title behaves as floating.
You need to take into account the location of the chart, so if you use the 'left' and 'top' attributes, you can add on half the width of the plot and subtract half the width of your text bounding box. This would yield the exact center:
text = chart.renderer.text("My Text").add(); textBBox = text.getBBox(); x = chart.plotLeft + (chart.plotWidth * 0.5) - (textBBox.width * 0.5); y = chart.plotTop + (chart.plotHeight * 0.5) - (textBBox.height * 0.5); text.attr({x: x, y: y});
Apparently the bounding box will be 0s unless you add it first.
Correction:
y = chart.plotTop + (chart.plotHeight * 0.5) + (textBBox.height * 0.25);
So, my original thought, and this seemed fine, was that the text would be aligned by the upper left, however it is done by the bottom left instead. Thus, instead of subtracting half the height, we actually need to add it. What confuses me, and something I don't understand yet, is that to get the center you add only 25% of the height rather then 50%. Note: This does not appear to work on IE 7 or 8.
http://jsfiddle.net/NVX3S/2/
<- Centered text that works in all browers
What this new update does is it adds a new element using jquery after the chart is done. This works in all browers that I have tested (including IE7, 8, 9, Firefox and Chrome).
var textX = chart.plotLeft + (chart.plotWidth * 0.5); var textY = chart.plotTop + (chart.plotHeight * 0.5); // The width and height need to be calculated properly, so I made it a span. var span = '<span id="pieChartInfoText" style="position:absolute; text-align:center;">'; span += '<span style="font-size: 32px">Upper</span><br>'; span += '<span style="font-size: 16px">Lower</span>'; span += '</span>'; $("#addText").append(span); span = $('#pieChartInfoText'); span.css('left', textX + (span.width() * -0.5)); span.css('top', textY + (span.height() * -0.5));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With