How to add text to chart.js data?

by giovanny.lueilwitz , in category: Javascript , 5 months ago

How to add text to chart.js data?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , 5 months ago

@giovanny.lueilwitz 

You can add text to a Chart.js data by using the "options" object in the configuration of the chart. You can specify the text you want to display on the chart by adding a "text" property under the "tooltips" object. Here's an example:

 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 chartData = {
  labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
  datasets: [{
    label: 'Sales',
    data: [100, 200, 300, 400, 500, 600, 700],
  }]
};

var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {
  type: 'line',
  data: chartData,
  options: {
    tooltips: {
      callbacks: {
        label: function(tooltipItem, data) {
          var dataset = data.datasets[tooltipItem.datasetIndex];
          var currentValue = dataset.data[tooltipItem.index];
          return 'Sales: ' + currentValue;
        }
      }
    }
  }
});


In this example, we are adding a callback function to the "label" property under the "tooltips" object. This function takes the tooltipItem and the data as arguments and returns the text that you want to display on the chart. In this case, we are displaying the sales value for each data point.


You can customize the text and formatting according to your requirements by modifying the callback function.