Search code examples
html5-canvaslabeljqplotangledonut-chart

Adding labels to a jqplot donut chart on an angle


I am needing to add labels to a donut plot at an angle, as shown in the image. I can only find information about angled text in relation to axis labels. Is there an easy way to do this for a donut chart? I don't mind making some changes inside the jqplot renderer, or just figuring out the angles and drawing the text on the overlay canvas — I'm just wondering if anyone has done this or knows a better way.


Solution

  • Answering my own question: I found that there is no provision to rotate labels in a donut chart - they are stored on the page as tags. However it is quite easy to draw them onto the overlay canvas after the chart is loaded.

    var co = plot3.plugins.canvasOverlay;
    var fiftiesSeries = plot3.series[0];
    
    var ctx=co.canvas._ctx;
    ctx.font="10px arial";
    for (var i = 0; i < fiftiesSeries.gridData.length; i++) {
        if (fiftiesSeries.gridData[i][0]) {
            var targetX = fiftiesSeries._center[0] + ((fiftiesSeries._radius) * Math.sin(fiftiesSeries.gridData[i][1] - (fiftiesSeries.gridData[i][2] * Math.PI)));
            var targetY = fiftiesSeries._center[1] - ((fiftiesSeries._radius) * Math.cos(fiftiesSeries.gridData[i][1] - (fiftiesSeries.gridData[i][2] * Math.PI)));
    
            ctx.setTransform(1, 0, 0, 1, 0, 0); // reset
            ctx.translate(targetX, targetY);
            ctx.rotate(fiftiesSeries.gridData[i][1] - ((fiftiesSeries.gridData[i][2] + 0.5) * Math.PI));
            ctx.fillText(fiftiesSeries.gridData[i][0], 3, 3);
        }
    }
    

    I hope this helps someone.