Chartjs-How to provide different labels in chart.js for toolbox and axis

0👍

It’s called a tooltip and you can read more about it here. Basically, you have to make a callback to the title and label to change the x-axis and y-axis of the tooltip respectively. Here’s how it would look:

boxLabels = ['2020-05-26', '2020-08-26', '2020-11-26', '2021-02-26', '2021-05-26', '2021-08-26', '2021-11-26', '2022-02-26', '2022-05-26'];  

options: {
    plugins: {
        tooltip: { 
            callbacks: { 
                title: function(context) {
                    let title = context[0].label || boxLabels[context[0].dataIndex];
                    return title;
                 },
                 label: function(context) {
                    let label = context.dataset.label + ": " + context.dataset.data[context.datasetIndex];
                    return label;
                 }
            }
        }
    }
};

Note that context for title returns an array, so you have to index it to get the element. See the snippet bellow for a whole example.

chartLabels = ['2 years ago','','','','1 year ago','','','','Today'];
  chartData = [0,0,0,0,0.13,0.08,0,0,0.1];
  yMax = 3;
  boxLabels = ['2020-05-26', '2020-08-26', '2020-11-26', '2021-02-26', '2021-05-26', '2021-08-26', '2021-11-26', '2022-02-26', '2022-05-26'];

const data = {
    labels: chartLabels,
    datasets: [{
        label: 'My Value XYZ',
        data: chartData,
        tension: 0.5,
    }]
};
const config = {
    type: 'line',
    data: data,
    options: {
        plugins: {
            legend: {
                display: false
            },
            tooltip: { 
                        callbacks: { 
                            title: function(context) {
                                let title = context[0].label || boxLabels[context[0].dataIndex];
                        return title;
                        },
                    label: function(context) {
                                let label = context.dataset.label + ": " + context.dataset.data[context.datasetIndex];
                        return label;
                        }
                    }
                },
        },
        scales: {
            x: {
                grid: {
                    display: false
                },
                ticks: {
                    autoSkip: false,
                    maxRotation: 0,
                    minRotation: 0
                }
            },
            y: {
                min: 0,
                max: yMax,
                grid: {
                    display: false
                }
            }
        }
    }
};
new Chart('chart-myvalues',config);
<html>
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>

    <canvas id="chart-myvalues" width="160" height="90"></canvas>
  <script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
  </body>
</html>

Leave a comment