[Chartjs]-Keeping scales in sync across multiple graphs or dynamically changing scales

3👍

Let’s assume we have chart1 and chart2. In order to keep scales in sync across the both charts, first define updateScales() as follows.

function updateScales() {
    var datasets = chart1.data.datasets.concat(chart2.data.datasets);
    chart1.options.scales.yAxes[0].ticks = chart2.options.scales.yAxes[0].ticks = {
        suggestedMin: Math.min(...datasets.map(function(dataset) {
            return Math.min(...dataset.data.map(function(value) {
                return value.y;
            }));
        })),
        suggestedMax: Math.max(...datasets.map(function(dataset) {
            return Math.max(...dataset.data.map(function(value) {
                return value.y;
            }));
        }))
    };
    chart1.update();
    chart2.update();
}

Then, call updateScales() at the end of onRefresh in the both charts.

onRefresh: function(chart) {
    // Update your datasets here
    // ...
    updateScales();
}

See also this example: https://jsfiddle.net/nagix/se2ank5z/

Leave a comment