Search code examples
highchartsrenderer

adding labels exactly above x-axis categories in highcharts


I tried to put labels but I am not able to locate the exact location of xAxis_categories realtive to graph. So if width is varied text gets disturbed and not remained aligned with categories http://jsfiddle.net/akataria/qx4snpvb/8/

startX = chart.xAxis[0].minPixelPadding + chart.xAxis[0].left ,
startY = chart.plotTop,
debugger;
r.text('19% yoy increase ', startX , startY)
.css({
color: '#4572A7',
fontSize: '11px',
}).add();

Solution

  • You can render the text once, then look at the bounding box of the Element to determine the width of the text, and then use this information to create a correctly positioned text by rendering it again.

    For example:

    var element = r.text('19% yoy increase ', 0 , 0)
    .css({
        fontSize: '11px'
    }).add();
    
    var width = element.getBBox().width;
    element.destroy();
    
    r.text('19% yoy increase ', data[0].plotX + chart.plotLeft - (width/2) , startY)
    .css({
        color: '#4572A7',
        fontSize: '11px'           
    }).add();
    

    See this JSFiddle for a demonstration.