[Chartjs]-Chart.js Auto Fit Failing

2๐Ÿ‘

โœ…

I have a working solution.

Define a function getMax() which takes in a chart and returns the maximum value of all the visible datasets.

var getMax = function(chart) {
    datasets = chart.data.datasets;
    max = 0;
    for(var i=0; i<datasets.length; i++) {
        dataset=datasets[i]
        if(chart.data.datasets[i].hidden) {
            continue;
        }
        dataset.data.forEach(function(d) {
            if(typeof(d)=="number" && d>max) {
                max = d
            }
        })
    }
    return max;
}

Then to options.legend, add an onClick function to call it and reset the y-axis suggestedMax to that max value plus 100 (you can tune this however you want):

  options: {
    <...>
    legend: {
      display: true,
      labels: {
        fontColor: "white",
      },
      onClick: function(e, legendItem) {
        di=legendItem.datasetIndex
        myBarChart.data.datasets[di].hidden = !myBarChart.data.datasets[di].hidden;
        myBarChart.options.scales.yAxes[0].ticks.suggestedMax=getMax(myBarChart)+100;
        myBarChart.update()
      }
    }
  }

Leave a comment