javascript - 在饼图上显示标签而不是数据值 Chart.js

标签 javascript chart.js

我使用 Chart.js 来制作图表。我今天发现了原始 Chart.js 的新插件。

Plugin

在我添加<script>之后使用该插件标记,它会自动将值应用于我的所有图表。它看起来很棒,但它显示的是数值。我如何让它在饼图上显示标签而不是值?我找到了一些关于该主题的帖子,但它们包含不同的命令,我尝试了所有可能的方法,但它没有改变任何东西。另外,为了将来,请告诉我如何关闭特定图表的显示值:)

fillPie()
{
    // Three arrays have same length
    let labelsArr = [];    // Array with some names
    let values  = [];   // Array with values
    let randomColor  = [];

    var ctx = document.getElementById('pie-chart').getContext('2d');
    var chart = new Chart(ctx, {

        // The type of chart we want to create
        type: 'pie',

        // The data for our dataset
        data: {
            labels: labelsArr,    // I want it to show these labels
            datasets: [{
                backgroundColor: randomColor, 
                data: values,     // It shows these values
                hoverBackgroundColor: "#fba999"
            }]
        },

        // Configuration options go here
        options: {
            legend: {
                display: false
            }
        }
    });
}

enter image description here

最佳答案

您可以在插件的文档中找到答案: https://chartjs-plugin-datalabels.netlify.com/guide/formatting.html#custom-labels

options: {
  plugins: {
    datalabels: {
      formatter: function(value, context) {
        return context.chart.data.labels[context.dataIndex];
      }
    }
  }
}

开发人员 simonbrunel explained on GitHub如何全局或针对特定数据集禁用该插件。以下是来自 GitHub 链接的引用:

That should be possible by disabling labels for all datasets via the plugin options at the chart level using the display option, then enable labels per dataset at the dataset level (dataset.datalabels.*):

new Chart('id', {
  data: {
    datasets: [{
      // no datalabels for this dataset
    }, {
        datalabels: {
          // display labels for this specific dataset
          display: true
        }
    }
  },
  options: {
    plugins: {
      datalabels: {
         // hide datalabels for all datasets
         display: false
      }
    }
  }
})

You can also globally disable labels for all charts using:

// Globally disable datalabels
Chart.defaults.global.plugins.datalabels.display = false

关于javascript - 在饼图上显示标签而不是数据值 Chart.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59103812/

相关文章:

javascript - 为什么默认的 Chart.js 图例框是透明矩形?

javascript - 我怎样才能让这个javascript函数调用自己?

javascript - Google Plus One Button - 如何添加回调?

javascript - 输入范围拇指 css 在 chrome 中不起作用

javascript - 如何克服 ReactJS 中的 CORS 问题

javascript - 无法移动我的范围选择器

javascript - 如何使用新的 JSON 数据刷新 jsTree?

django - 如何将我的 sqlite 数据传递给 django 并制作图表?

node.js - Chartjs 在 Angular2 应用程序中的使用

javascript - ionic 不从变量返回数据