How to populate dataset legends in chart.js?

by raven_corwin , in category: Javascript , 6 months ago

How to populate dataset legends in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 6 months ago

@raven_corwin 

To populate dataset legends in Chart.js, you can use the legend configuration option in the chart options object.


Here is an example of how to set up the legend:

 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 myChart = new Chart(ctx, {
  type: 'line', // or any other chart type
  data: {
    labels: ['Label 1', 'Label 2', 'Label 3'], // x-axis labels
    datasets: [{
      label: 'Dataset 1',
      data: [1, 2, 3], // y-axis values
      backgroundColor: 'rgba(255, 99, 132, 0.2)' // optional background color
    },
    {
      label: 'Dataset 2',
      data: [3, 2, 1],
      backgroundColor: 'rgba(54, 162, 235, 0.2)'
    }]
  },
  options: {
    legend: {
      display: true, // set to true to display the legend
      position: 'top', // choose 'top', 'bottom', 'left', 'right' or 'chartArea' for the position
      labels: {
        fontColor: 'rgb(255, 99, 132)' // optional font color for legend labels
      }
    }
  }
});


In this example, the datasets array contains the data for each dataset, and the labels array contains the labels for the x-axis.


The legend configuration option is set to display: true to show the legend. You can also customize the legend's position and label font color by modifying the position and labels properties.


Make sure to replace ctx with your own canvas context when creating the chart.


This example is for a line chart, but you can apply the same configuration to other types of charts like bar, pie, etc.