Boat
Boat

Reputation: 422

ChartJS automatically scaled chart has undefined min and max

ChartJS defines options.scales[scaleId].min as "User defined minimum number for the scale, overrides minimum value from data". One would think that if I haven't defined minimum value, the minimum value derived from data would be available. However, that is not the case.

I need to add my data and labels dynamically, and derive zooming and panning limits from the automatically scaled data. Otherwise I can zoom and pan far out from the actual data, which looks ugly.

In this Stackblitz you can see, when I try to log axis scales min and max, they are undefined, but when I log the whole chart object, I can see that the scales have correct min and max values derived from data.

Is there a way to retrieve min and max values of automatically scaled data? Without looping each hundreds of thousands items long dataset arrays myself?

Upvotes: 2

Views: 673

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31371

Yes it is possible, the options object only contains the user defined options. You can go into the scales object that is directly on the chart to retrieve the min and max like so

const chart = new Chart(ctx, config);
const max = chart.scales[scaleId].max;
const min = chart.scales[scaleId].min;

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange'
      }
    ]
  },
  options: {}
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);

console.log(`Max: ${chart.scales.y.max}, Min: ${chart.scales.y.min}`)
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.js"></script>
</body>

Upvotes: 4

Related Questions