0

我需要用 React-Chart-js2 制作甜甜圈图。图表应如下所示 在此处输入图像描述

问题:

  1. 我在图表中添加了数据(12%、10% 等)。但是如何添加标签(1星,2星)?
  2. 如何将文本(1234 总反馈)放在图表的中心?
  3. 是否可以突出显示图像中提到的悬停部分?

代码: 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>
)
}
4

1 回答 1

0

您可以通过注册函数来使用插件

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

你的函数看起来像:

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();
  };
于 2021-05-21T11:14:12.337 回答