Search code examples
reactjschart.jsreact-chartjsreact-chartjs-2

Chartjs: make square legends


With react-chartjs-2, creating Bar Graph as below. I am trying to make the legends in square shape rather than default rectangle.

I applied boxWidth: 10 as below but it doesn't work, Is there any other possible alternatives to generate a square legend

const sample_data = {
  labels: ['Item1', 'Item2'],
  datasets: [
    {
      data: [10, 10, 50],
      borderWidth: 1,
      backgroundColor: 'yellow',
    },
    { data: [20, 20, 20], 
      borderWidth: 1,
      backgroundColor: 'green' 
    },
  ],
};
const sample_options = {
  responsive: true,
  legend: {
    boxWidth: 10, // Also 0 doesn't make any change
  },
...
};
<Bar data={sample_data} options={sample_options} />;

Solution

  • You will have to put the boxWidth in the labels part of the legend options as stated in the documentation: https://www.chartjs.org/docs/latest/configuration/legend.html#legend-label-configuration

    var options = {
      type: 'line',
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            borderWidth: 1
          },
          {
            label: '# of Points',
            data: [7, 11, 5, 8, 3, 7],
            borderWidth: 1
          }
        ]
      },
      options: {
        legend: {
          labels: {
            boxWidth: 10
          }
        },
        scales: {
          yAxes: [{
            ticks: {
              reverse: false
            }
          }]
        }
      }
    }
    
    var ctx = document.getElementById('chartJSContainer').getContext('2d');
    new Chart(ctx, options);
    <body>
      <canvas id="chartJSContainer" width="600" height="400"></canvas>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
    </body>