Adding Multiline text to Highcharts

Posted by ryansouthgate on 15 Mar 2016

In this post I’m going to detail how to add multiline text (and centre it) in Highcharts.

Note: You could do this in pure html - however I’m going to be doing it using the Highcharts renderer (it uses SVG) as I need the text in the SVG. As it will be sent to the server and rendered into a PNG by an SVG-to-Bitmap library (see that post here)

If you want to skip ahead and see the code - the Plnkr is here: http://plnkr.co/bjKmFTg8tFoj6wmWLRHT

Below is the Gist:

First set some text, I’ve put a <br/> in the text as I want it to appear on multiple lines - note \n\r does not work.

After defining the options for the chart, I’ve created a function called setText.

This gets the chart and defines some attributes for the SVG text element that will be created. I’ve set the z-index to 5, the x and y to the middle of the chart (width / 2).

I call chart.rendered.text with the passed in text. Set the text-anchor property (css) of the text element to “middle” - we want the multiline text centered!

Then call .add() on the text element returned from Highcharts.

This function can be called at anytime throughout the Chart’s lifecycle and it will render the text. If you want to update the text, you could give it a unique class attribute which will allow you to jQuery it (for example) then set it to the new text passed in.

Everytime you call the add() method it will add another text element - so just remember that and ensure you clean up after yourself if you ever need to remove/modify any.

Note: If you’re exporting the SVG

If you’re exporting SVG from this chart - and want the text to remain in the exported SVG, you’ll not be able to use chart.getSVGForExport(). What this function does is reconstruct an identical chart (based on series, data and various other Highcharts options) - therefore your added text will be lost. Instead - the following calls will grab the SVG straight out of the rendered chart - and will bypass Highcharts creating you a replica (without the text).

var chartHtml = chart.getHtml();
var svg = chart.sanitize(chartHtml);


comments powered by Disqus