Search code examples
reactjschart.jsreact-chartjs-2

how to change display and styles of the labels in react-chartjs-2


I am using react-chartjs-2 and I want the labels to be circular. also I want the chart itself with labels have a display of inline-block so that I get something like this photo: [the desired design1

but what I actually get is this : the design of chartjs-2

and my code is here :

  let _data = data;
                let _backgroundColor = [];
                let _borderColor = [];
                setDataShareholder(res);
                res.value.forEach(item => {
                    let rgb = `${random(0, 255)}, ${random(0, 255)}, ${random(0, 255)}`;
                    _backgroundColor.push(`rgba(${rgb}, 0.5)`)
                    _borderColor.push(`rgba(${rgb}, 1)`)
                });
                _data.labels = res.value.map(item => item.name)
                _data.datasets = [{
                    data: res.value.map(item => Number(item.violationsCount)),
                    backgroundColor: _backgroundColor,
                    borderColor: _borderColor,
                    borderWidth: 1
                }];
                setData(_data);

usage :

  import { Doughnut } from 'react-chartjs-2';

  <Doughnut data={data} />

please help me if you can. thanks


Solution

  • You can configure the chart options. You can set the legend position to right and pointStyle to circle:

    const options = {
      type: 'doughnut',
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
          backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
        }]
      },
      options: {
        plugins: {
          legend: {
            position: 'right',
            labels: {
              usePointStyle: true,
              pointStyle: 'circle'
            }
          }
        }
      }
    }
    
    const 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/3.7.1/chart.js"></script>
    </body>