How to add custom label for line chart from chart.js?

by muriel.schmidt , in category: Javascript , a year ago

How to add custom label for line chart from chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 6 months ago

@muriel.schmidt 

To add a custom label for a line chart in Chart.js, you can use the "tooltips" option to customize the tooltip display. Here's an example of how you can add a custom label for a line chart:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'Custom Label',
            data: [10, 20, 15, 25, 30, 35, 40],
            borderColor: 'blue',
        }]
    },
    options: {
        tooltips: {
            callbacks: {
                title: function(tooltipItem, data) {
                    return 'Custom Label: ' + data.labels[tooltipItem[0].index];
                },
                label: function(tooltipItem, data) {
                    return 'Value: ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
                }
            }
        }
    }
});


In this example, we have added a custom label for the line chart by using the tooltips callback functions. The title function is used to customize the title of the tooltip, and the label function is used to customize the content of the tooltip. You can modify the content of the custom label as needed to display the information you want.