Search code examples
javascriptjqueryecmascript-6highchartspie-chart

Create multiple Pie Highcharts for multiple series


I am trying to draw a highchart using JSON data. My data has multiple series. Because of that 2 pie charts are created overlapping each other. Is there a way for me to draw the multiple highcharts next to each other instead?

My JSON, code and working example of the pie charts overlapping each other:

let data = [{
    "name": "cakes",
    "data": [
        [
            "us",
            149045
        ],
        [
            "es",
            41746
        ],
        [
            "uk",
            37640
        ],
        [
            "au",
            16594
        ]
    ],
    "marker": {
        "symbol": "circle"
    }
}, {
    "name": "pie",
    "data": [
        [
            "us",
            128845
        ],
        [
            "es",
            35752
        ],
        [
            "uk",
            32246
        ],
        [
            "au",
            14333
        ]
    ],
    "marker": {
        "symbol": "circle"
    }
}]

Highcharts.chart('container', {
        chart: {
            type: 'pie',
            zoomType: 'xy'
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    // format: '{series.data[0]} <b>{point.percentage:.1f}%</b>'
                }
            },
        },
        series: data
    });
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/data.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>

<div id="container"></div>

How do I get pie charts next to each other rather than one on top of the other? One for cakes and one for pies?


Solution

  • You can create multiple charts with dynamically calculated styles:

    data.forEach(function(dataEl) {
        const createdDiv = document.createElement('div');
        createdDiv.style.display = 'inline-block';
        createdDiv.style.width = 100 / data.length + '%'
    
        mainContainer.appendChild(createdDiv);
    
        Highcharts.chart(createdDiv, {
            ...,
            series: [dataEl]
        });
    });
    

    Live demo: https://jsfiddle.net/BlackLabel/jn4p2gq8/


    Or one chart with dynamically calculated center property for each series.

    API Reference: https://api.highcharts.com/highcharts/series.pie.center