chartjs / Chart.js

Simple HTML5 Charts using the <canvas> tag
https://www.chartjs.org/
MIT License
63.96k stars 11.89k forks source link

Zooming out does not work if labels are numbers #10908

Open dphdmn opened 1 year ago

dphdmn commented 1 year ago

Following the example on this page https://www.chartjs.org/chartjs-plugin-zoom/master/guide/usage.html

Changing labels to numbers:

  type: 'line',
  data: {
    labels: [1,2,3,4,5,6,7],
    datasets: [{
      label: 'My First Dataset',
      data: [65, 59, 80, 81, 56, 55, 40],
      fill: false,
      borderColor: 'rgb(75, 192, 192)',
      tension: 0.1
    }]
  },
  options: {
    plugins: {
      zoom: {
        zoom: {
          wheel: {
            enabled: true,
          },
          pinch: {
            enabled: true
          },
          mode: 'x',
        }
      }
    }
  }
};

And now I can zoom in, but can't zoom out. Could not google anything about such problem, that is really weird and took few hours to figure out trying different modes and settings. Well, actually i found 1 question without answer: https://stackoverflow.com/questions/71383205/chartjs-v-3-7-1-zoom-out-not-working-after-zooming-in-too-much (but that was not really helpful, although this also uses numbers as labels, so probably the same issue)

Easy fix for the problem: using .toString() on items of the array.

After trying different numbers i'm getting different block of the zooming out, for example [14,44,58,4,5,6,7] blocks it with 4 on the right, [1,44,58,4,5,6,7] block around 1, [44,3,3,44,54,64,74] works well, [44,1,3,44,54,64,74] blocks with 3 on the right

kurkle commented 1 year ago

Category scale (the default) expects strings, and is using array indices (numbers) internally, to point to the locations. It probably misbehaves when supplied labels are numbers. I think it should throw an error in this case.

Andersama commented 1 week ago

Can confirm this is still an issue and that the (temporary) solution is to change the labels from numbers to strings.