[Chartjs]-ChartJS display legend

14👍

Based on the code that you supplied in your question, it looks like you forgot to add labels data in your chart data object. Without this information chartjs is not able to generate your axis and map each dataset data to it.

Also, since you mentioned you wanted the legend to be below the chart, I added the display: bottom option. Here is the working code.

var ctx = document.getElementById("mybarChart").getContext("2d");

var mybarChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Votes'],
    datasets: [{
      label: '# of Votes',
      backgroundColor: "#000080",
      data: [80]
    }, {
      label: '# of Votes2',
      backgroundColor: "#d3d3d3",
      data: [90]
    }, {
      label: '# of Votes3',
      backgroundColor: "#add8e6",
      data: [45]
    }]
  },

  options: {
    legend: {
      display: true,
      position: 'bottom',
      labels: {
        fontColor: "#000080",
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

Here is a working codepen example as well.

2👍

With the latest version of the chart.js (3.6.0), you can control the Legend display with the following code:

  const options = {
    plugins: {
    ...
      legend: {
        position: "right", // by default it's top
      },
    ...
    },
  };

I know this has been here for so long but might help someone who faced the same issue as me in the future.

Leave a comment