0

I need to make Doughnut chart with React-Chart-js2 . Chart should look like below enter image description here

Questions:

  1. I have added Data(12%,10% etc) in the chart. But how to add labels (1 star, 2star)?
  2. How to put text (1234 Total Feedback) in the center of chart?
  3. Is it possible to highlight the hovered portion as mentioned in the image?

Code: const donutChart = {

labels:['1 star','2 star','3 star','4 star'],
datasets: [{
  data: [10, 50, 10,40],
  backgroundColor: [
    '#808080',
    '#808080',
    '#808080',
    '#808080'

    ],
    hoverBackgroundColor: [
    '#FF5733',
    '#FF5733',
    '#FF5733',
    '#FF5733'
    ],
   
    hoverBorderColor : [
      '#FF5733',
      '#FF5733',
      '#FF5733',
      '#FF5733'
      ],
}
]

}

function Reports() {
 
        return (
<div>
          <Doughnut 
          data={donutChart}
          options={{
              padding:"0px",
              responsive:true,
              maintainAspectRatio:true,
              defaultFontSize:"14px",
              title:{
                display:true,
                text:'Total Feedback',
                fontSize:30,
              },
              legend:{
                  display:false,
              },
              plugins:{
                  datalabels: {
                      color:'red',
                      anchor: "start",
                      align:"end",
       
                  }
              } 
          }}
          />
          </div>
)
}
Akanksha
  • 123
  • 1
  • 3
  • 14
  • this will help you - https://stackoverflow.com/questions/20966817/how-to-add-text-inside-the-doughnut-chart-using-chart-js – Madhuri Nov 30 '20 at 21:27

1 Answers1

0

You can use plugins by registering functions

     <Doughnut
        data={data}
        options={options}
        plugins={[
          {
            beforeDraw: function (chart) {
              drawInnerText(chart);
            },
          },
        ]}
      />

Your function would look like:

const drawInnerText = (chart) => {
    let ctx = chart.ctx;
    ctx.restore();
    const fontSize = (chart.height / 114).toFixed(2);
    ctx.font = fontSize + 'em sans-serif';
    ctx.textBaseline = 'middle';
    const dataArrValues = chart.config._config.data.datasets[0].data;
    let text =
      chart.tooltip._active.length > 0
        ? `${Math.round(
            (dataArrValues[chart.tooltip._active[0].datasetIndex] /
              dataArrValues.reduce((a, b) => a + b)) *
              100
          )}%`
        : `${Math.round(
            (dataArrValues[0] / dataArrValues.reduce((a, b) => a + b)) * 100
          )}%`;
    let textX = Math.round((chart.width - ctx.measureText(text).width) / 2);
    let textY = chart.height / 2 + chart.legend.height / 2;
    ctx.fillText(text, textX, textY);
    ctx.fillStyle = '#fff';
    ctx.save();
  };
a-s-r-789
  • 61
  • 1
  • 6