甜甜圈图中数据标签的自定义 ng2-charts

Customization of Data Labels in doughnut chart ng2-charts

我想在圆环图中显示自定义数据标签。到目前为止,我已经实现了数据标签来显示百分比值。它看起来像这样: Current design

我希望图表显示这样的数据标签:Required design

这是我的图表选项:

chartOptions: {
   legend: { display: true, position: 'bottom', labels: { fontSize: 10, usePointStyle: true }},
   plugins: {
     datalabels: {
        formatter: (value: number, ctx: { chart: { data: { datasets: { data: any; }[]; }; }; }) => {
           let sum = 0;
           let dataArr = ctx.chart.data.datasets[0].data;
           dataArr.map((data: number) => {
               sum += data;
           });
           let percentage = (value*100 / sum) +"%";
              return percentage;
        },
        color: '#fff',
    }
  }
},

如果有人能在这方面帮助我,那将非常有帮助。谢谢

backgroundColorborderRadius 添加到数据标签。

检查下面的代码片段来实现这一点。

Chart.register(ChartDataLabels);

var doughnutCtx = document.getElementById("doughnutChart").getContext('2d');

var myChart = new Chart(doughnutCtx, {
  type: 'doughnut',
  data: {
    labels: ['January', 'February', 'March', 'April', 'May'],
    datasets: [{
      data: [50, 60, 70, 180, 190],
       backgroundColor: [ 'rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)', 'rgb(54, 162, 235)', ],
    }]
  },
  options: {
    plugins: {
      datalabels: {
       display: true,
        formatter: (value) => {
          return value + '%';
        },
        align: 'center',
        backgroundColor: 'white',
        borderRadius: 100,
        padding:10,
        font: {
          size: 18,
        }
      }
    }
  }
});
canvas{
  max-height: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
<div>
  <canvas id="doughnutChart"></canvas>
</div>