Chartjs-Chart.js cartesian axes – Modifying tool-tip based on which y-axis the data corresponds to

0👍

After further inspection into variable d (data), it actually returns the yAxisID attribute. Which is exactly what is needed for matching the data points to their corresponding y-axes. yAxisID is defined in y-axes, so you can test against the names you have provided.

const axisId = d.datasets[t.datasetIndex].yAxisID; // returns axisID

See here for tooltip documentation.

The following code now works, test axis id for the defined axis and adjust t.yLabel based on it:

tooltips: {
    callbacks: {
      label: function(t, d) {
        const xLabel = d.datasets[t.datasetIndex].label;
        const axisId = d.datasets[t.datasetIndex].yAxisID; // returns axisID, defined below
        if (axisId === "first-y-axis")
          return xLabel + ": " + t.yLabel.toLocaleString("en-US", {
            style: "currency",
            currency: "USD"
          });
        return xLabel + ': ' + t.yLabel + "%"; // if axis ID does not match first, then %
      }
    }
}

Leave a comment