How to customize y-axis labels on a chart.js line chart?

Member

by addison , in category: Javascript , 9 months ago

How to customize y-axis labels on a chart.js line chart?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 9 months ago

@addison 

To customize the y-axis labels on a Chart.js line chart, you can use the yAxes option in the configuration object for the chart. 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
26
27
28
var chartData = {
  labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
  datasets: [{
    label: 'My Dataset',
    data: [10, 15, 7, 12, 9],
    borderColor: 'red',
    fill: false
  }]
};

var chartOptions = {
  scales: {
    yAxes: [{
      ticks: {
        // Customize y-axis label format
        callback: function(value, index, values) {
          return value + '°C';
        }
      }
    }]
  }
};

var lineChart = new Chart(document.getElementById('myLineChart'), {
  type: 'line',
  data: chartData,
  options: chartOptions
});


In the callback function of the ticks option, you can specify your own logic to format the y-axis labels based on the value parameter. In the provided example, the labels are formatted as degrees Celsius.