0

I have two stacked column charts next to each other, sharing the same categories, and I would like them to both be controlled by the same legend. So that there is only one visible legend, but clicking the items affects both charts.

I found this jsfiddle that accomplishes this using JQuery, and this StackOverflow post that accomplishes it in React using class components.

$(function () {
$('#container1').highcharts({
    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    legend: {
        enabled: false
    },

    series: [{
        id: 'someId',
        name: 'Apples',
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
        }, {
        id: 'someId',
        name: 'Bananas',
            data:   [71,74,76,77,63,74,72,46,23.8,62,59.6,40.5]
        
    }]
});
$('#container2').highcharts({
    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    plotOptions: {
        series: {
            events: {
                legendItemClick: function (event) {
                    var XYZ = $('#container1').highcharts(),
                        series = XYZ.get(this.options.id); //get corresponding series

                    if (series) {
                        if (this.visible) {
                            series.hide();
                        } else {
                            series.show();
                        }
                    }
                }
            }
        }
    },

    series: [{
        id: 'someId',
        name: 'Apples',
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
        }, {
        id: 'someId',
        name: 'Bananas',
            data:   [71,74,76,77,63,74,72,46,23.8,62,59.6,40.5]
    }]
});

});

However I am having trouble figuring out how to accomplish this using functional components in React, since you can't use the "this" keyword to access the chart options, but putting the click event function outside of the functional component makes it impossible to use a DOM ref to the other chart.

Sarah
  • 68
  • 1
  • 5
  • 1
    Highcharts has an official wrapper for react. Please try using that - https://github.com/highcharts/highcharts-react – A G May 16 '22 at 13:33
  • I am using the Highcharts wrapper, but I cannot figure out any way to access the chart options and the second chart ref from inside the onLegendClick method – Sarah May 17 '22 at 10:01

0 Answers0