0

I am trying to create a Chart.js line chart with a set number of ticks at fixed positions on the Y-axis. The Y-axis represents distance, but I only want to display certain fixed points along the axis.

Each point has a label independent from its actual value, and each label-distance pair has a unique key. Note that distances do not have to be unique:

let map = {
  1: {
    label: "A",
    distance: 0,
  },
  2: {
    label: "B",
    distance: 0.4,
  },
  3: {
    label: "C",
    distance: 0.7,
  },
  4: {
    label: "D",
    distance: 1.0,
  },
  5: {
    label: "E",
    distance: 1.0,
  },
  6: {
    label: "F",
    distance: 1.5,
  },
};

I tried implementing a callback for tick labels in the chart options:

let options = {
  y: {
    ticks: {
      stepSize: 0.1, // creates too many unnecessary ticks
      callback: function (value, index, ticks) {
        // inefficient, fails with duplicate distances
        for (const s of Object.values(map)) {
          if (s.distance === value) {
            return s.label;
          }
        }
        return null;
      },
    },
  },
};

But this will fail if one of my distances isn't a tick due to the range, and it will not be able to show multiple ticks with the same distance.

I saw this answer but I'm not sure it will work with duplicate distances.

Does chart.js support something like this? I haven't found anything.

jonah0
  • 23
  • 7
  • 1
    Does this answer your question? https://stackoverflow.com/a/69675479/2358409 – uminder Jul 29 '22 at 06:10
  • Yes, the updated solution works great! However, sometimes certain ticks don't render because they are too close together for the size of the chart. Is there any way to force them to always render? (Even if they are almost on top of each other) – jonah0 Jul 29 '22 at 16:29
  • 1
    Try to set `autoSkip: false` (see https://www.chartjs.org/docs/latest/axes/cartesian/#common-tick-options-to-all-cartesian-axes) – uminder Jul 30 '22 at 10:59

0 Answers0