ChartJS:百分比标签

ChartJS: Percentage labels

首先,我想说我是一名学习编程一个月左右的学生,所以希望看到很多错误。

我正在使用 ChartJs 库中的图表的网站上工作。我有一个外圈,显示在公司工作的时间和达到月度目标所需的时间。内圈显示该月的天数和该月剩余的天数。这是代码:

const data = {
    labels: ['Summe', 'Noch um Ziel zu erreichen', 'Tage', 'Verbleibende Tage im Monat'],
    datasets: [
      {
        backgroundColor: ['#5ce1e6', '#2acaea'],
        data: [studenGesamt, (800 - studenGesamt)]
      },
      {
        backgroundColor: ['#cd1076', '#8b0a50'],
        data: [dayD, (23 - dayD)]
      },
  
    ]
  };

// Configuration of the pie chart
let outterChart = new Chart(chart, {
    type: 'pie',
    data: data,
    options: {
    responsive: true,
    plugins: {
      legend: {
        labels: {
          render: 'percentage',
          fontColor: ['green', 'white'],
          precision: 2,
          generateLabels: function(chart) {
            // Get the default label list
            const original = Chart.overrides.pie.plugins.legend.labels.generateLabels;
            const labelsOriginal = original.call(this, chart);

            // Build an array of colors used in the datasets of the chart
            var datasetColors = chart.data.datasets.map(function(e) {
              return e.backgroundColor;
            });
            datasetColors = datasetColors.flat();

            // Modify the color and hide state of each label
            labelsOriginal.forEach(label => {

              // Change the color to match the dataset
              label.fillStyle = datasetColors[label.index];
              
            });

            return labelsOriginal;
          }
        },
        onClick: function(mouseEvent, legendItem, legend) {
          // toggle the visibility of the dataset from what it currently is
          legend.chart.getDatasetMeta(
            legendItem.datasetIndex
          ).hidden = legend.chart.isDatasetVisible(legendItem.datasetIndex);
          legend.chart.update();
        }
      },
       tooltip: {
        callbacks: {
          label: function(context) {
            const labelIndex = (context.datasetIndex * 2) + context.dataIndex;
            return context.chart.data.labels[labelIndex] + ': ' + context.formattedValue;
          }
        }
      },
    }
  },
});

我想在饼图上显示饼图各部分的百分比。为此,我找到了插件“chartjs-plugin-labels”,并在脚本标签上添加了以下 link 以便我可以在我的网站上使用它:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<script src="script.js"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>

在我的代码中,我添加了以下代码(我没有在此处添加右括号,因为它们在代码的下方,我只是想展示代码的这一小部分):

plugins: {
      legend: {
        labels: {
          render: 'percentage',
          fontColor: ['green', 'white'],
          precision: 2,

但是,此代码无效,图表上未显示任何百分比。我假设我做错了什么,可能是在 CDN link 上或在代码本身上,但我想不通。如果有人可以帮助我,我将不胜感激!这是图表的图片,因此您可以了解我到底想要什么:

您尝试使用的插件已过时,不适用于 chart.js 版本 3,您可以使用 datalabels plugin

使用数据标签插件时,您需要使用 formatter 函数将值更改为百分比,并且您需要注册该插件:

Chart.register(ChartDataLabels);

const data = {
  labels: ['Summe', 'Noch um Ziel zu erreichen', 'Tage', 'Verbleibende Tage im Monat'],
  datasets: [{
      backgroundColor: ['#5ce1e6', '#2acaea'],
      data: [200, (800 - 200)]
    },
    {
      backgroundColor: ['#cd1076', '#8b0a50'],
      data: [4, (23 - 4)]
    },

  ]
};

var ctx = document.getElementById('chartJSContainer').getContext('2d');

// Configuration of the pie chart
let outterChart = new Chart(ctx, {
  type: 'pie',
  data: data,
  options: {
    responsive: true,
    plugins: {
      datalabels: {
        color: 'white',
        formatter: (val, ctx) => {
          const totalDatasetSum = ctx.chart.data.datasets[ctx.datasetIndex].data.reduce((a, b) => (a + b), 0);
          const percentage = val * 100 / totalDatasetSum;
          const roundedPercentage = Math.round(percentage * 100) / 100
          return `${roundedPercentage}%`
        }
      },
      legend: {
        labels: {
          generateLabels: function(chart) {
            // Get the default label list
            const original = Chart.overrides.pie.plugins.legend.labels.generateLabels;
            const labelsOriginal = original.call(this, chart);

            // Build an array of colors used in the datasets of the chart
            var datasetColors = chart.data.datasets.map(function(e) {
              return e.backgroundColor;
            });
            datasetColors = datasetColors.flat();

            // Modify the color and hide state of each label
            labelsOriginal.forEach(label => {

              // Change the color to match the dataset
              label.fillStyle = datasetColors[label.index];
            });

            return labelsOriginal;
          }
        },
        onClick: function(mouseEvent, legendItem, legend) {
          // toggle the visibility of the dataset from what it currently is
          legend.chart.getDatasetMeta(
            legendItem.datasetIndex
          ).hidden = legend.chart.isDatasetVisible(legendItem.datasetIndex);
          legend.chart.update();
        }
      },
      tooltip: {
        callbacks: {
          label: function(context) {
            const labelIndex = (context.datasetIndex * 2) + context.dataIndex;
            return context.chart.data.labels[labelIndex] + ': ' + context.formattedValue;
          }
        }
      },
    }
  },
});
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.js"></script>
</body>