How to add labels or legends for all chart types in Chart.js and JavaScript?

Sometimes, we want to add labels or legends for all chart types in Chart.js and JavaScript.

In this article, we’ll look at how to add labels or legends for all chart types in Chart.js and JavaScript.

How to add labels or legends for all chart types in Chart.js and JavaScript?

To add labels or legends for all chart types in Chart.js and JavaScript, we use the chart’s generateLegend method.

For instance, we write

<div>
  <canvas id="chartDiv" height="400" width="600"></canvas>
  <div id="legendDiv"></div>
</div>

to add a canvas for the chart and a div for the legend.

Then we write

const data = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [
    {
      label: "Speed 1",
      fillColor: "rgba(220,220,220,0.2)",
      strokeColor: "rgba(220,220,220,1)",
      pointColor: "rgba(220,220,220,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(220,220,220,1)",
      data: [65, 59, 56, 24, 56, 55, 6],
    },
    {
      label: "Speed 2",
      fillColor: "rgba(151,187,205,0.2)",
      strokeColor: "rgba(151,187,205,1)",
      pointColor: "rgba(151,187,205,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(151,187,205,1)",
      data: [28, 1, 54, 76, 24, 12, 6],
    },
  ],
};

const myLineChart = new Chart(
  document.getElementById("chartDiv").getContext("2d")
).Line(data);
document.getElementById("legendDiv").innerHTML = myLineChart.generateLegend();

to create a chart with the canvas and the Chart constructor.

We call Line to create a line chart with the data.

Then we call myLineChart.generateLegend to return an HTML string with the legend’s content and set it as the innerHTML value of the div to show it.

Conclusion

To add labels or legends for all chart types in Chart.js and JavaScript, we use the chart’s generateLegend method.