reactjschart.js

How to modify the legend of Bar Chart


I am using chartjs with react

import { Chart,Line,Bar,Pie } from 'react-chartjs-2';

    var data = {
      options: {
        legend: {
          position : 'right',
        },
        title:{
          display: true,
          text : 'Total number of defects raised by each team across iterations'
        }
      },
      data:{
        labels:["Mon","Tue","Wed"],
        datasets:[{
          label: 'Action',
          data: [12,42,32],
          backgroundColor: 'rgba(255, 99, 132, 0.2)',
          borderColor: 'rgba(255, 99, 132, 1)',
          borderWidth: 1,
        }]
      }
    });

return <Chart type={"bar"} options={data['options']} data={data['data']}></Chart>

Now I want to use the options to change the design of legend.

It show the graph however, legend position doesn't change.

I am afraid it is something wrong around options setting.

How can I fix this?


Solution

  • you're setting options in Chart.js v3+. In the newer versions, the legend settings have changed. It should be inside plugins.legend, like this:

    options: {
      plugins: {
        legend: {
          position: 'right', 
        }
      },
      responsive: true,
      maintainAspectRatio: false
    }
    

    you can also make the following changes if needed further:

    // Register required components
    ChartJS.register(BarElement, CategoryScale, LinearScale, Title, Tooltip, Legend);