Search code examples
javascriptlabelrgraph

How do you avoid labels overlapping in a Pie chart?


I would like to avoid this situation of overlapping text labels in a Pie chart that I'm drawing:

A Pie chart with overlapping labels

Is there a 'recognised' way to do it? ie a particular text placement algorithm? And if not, then how to do it efficiently?

EDIT: So that it looks similar to this type of label placement: Overlapping Labels in Pie-Chart


Solution

  • UPDATED:

    I've got a better system to organise the labels which just lists the labels on the relevant side and then adds lines from each label to the appropriate segment.

    You can see an example here:

    https://www.rgraph.net/demos/pie-basic.html

    And the code to create that chart is:

    <script src="RGraph.common.core.js"></script>
    <script src="RGraph.pie.js"></script>
    
    <canvas id="cvs" width="350" height="250">
        [No canvas support]
    </canvas>
    
    <script>
        // A basic configuration for a Pie chart with just the labels
        // separated out into their own array. This is because the same
        // array is used for both the labels and the tooltips so
        // doing this makes for less upkeep when the time comes to
        // change things around.
        //
        // Also note that the stroke color has been set to transparent so
        // that there's no separation between the segments
        //
        labels = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    
        new RGraph.Pie({
            id: 'cvs',
            data: [20,1,1,1,1,1,1],
            options: {
                
                // This is the tooltip property using formatted tooltips
                tooltips: '%{property:myDaynames[%{index}]}<br /><span style="font-weight: bold; font-size:26pt">%{value_formatted}</span>',
                
                // The units that are appended to the %{value_formatted} value
                tooltipsFormattedUnitsPost: '%',
                
                // Some CSS values that are set on the tooltips so that you can customise them
                tooltipsCss: {
                    backgroundColor: 'white',
                    border: '3px solid black'
                },
    
                // A custom property - the formatted tooltips can then
                // access this to use the data inside the tooltip
                myDaynames: labels,
    
                shadow: false,
                colorsStroke: 'transparent',
                keyPositionGraphBoxed: false,
                
            }
        // Draw the chart
        }).draw();
    </script>