ChartJS Chart JS:显示没有getContext('2d ')的标签的百分比

vfh0ocws  于 2022-11-07  发布在  Chart.js
关注(0)|答案(1)|浏览(145)

我正在使用chartJs库来显示我从MySQL数据库中获得的数据。在下面的函数中,AddValuesToNavigatorChart获取浏览器数据和百分比数据,并将它们显示在饼图上。我需要知道的是,如何在我的标签中添加“%”?我发现使用getContent('2d ')..使用旧方法几乎没有答案,但它不起作用。这是一个函数:

function AddValuesToNavigatorChart(browsers, percentage) {
            checkNavigatorChart()
            const data = {
                labels: browsers,
                datasets: [{
                    data: percentage,
                    backgroundColor: [
                        'rgb(192,192,192)',
                        'rgb(255,0,0)',
                        'rgb(0,0,0)',
                        'rgb(105,105,105)'
                    ],
                    hoverOffset: 4
                }]
            };
            const config = {
                tooltips: {
                    enabled: false
                },
                type: 'pie',
                data: data,
                plugins: [ChartDataLabels],
                options: {
                    showTooltips: false,
                    plugins: {
                        datalabels: {
                            color: 'rgb(255,255,255)',
                            borderWidth: '2',
                            align: 'top'
                        },
                        legend: {
                            position: 'bottom',
                            align: 'center',
                            labels: {
                                boxWidth: 12,
                                padding: 15,
                                usePointStyle: true,
                                pointStyle: 'circle'
                            }
                        },
                        title: {
                            text: 'Navigator Chart',
                            display: true,
                            color: 'rgb(0,0,0)',
                            position: 'top'
                        }
                    }
                }
            };
            const NavigatorChart = new Chart(
                document.getElementById('NavigatorChart'),
                config
            );
        }
ds97pgxw

ds97pgxw1#

请提供您正在使用的chartjs版本。
您是否希望在工具提示的标签中显示%
对于v3.8.0版本,下面是我刚刚编写的工作代码Link
在选项中,您可以根据需要编辑工具提示的标签:

options: {
    plugins: {
      tooltip: {
        callbacks: {
          label: (tooltipItem) => {
              //tooltipItem is for the slice of the pie you are hovering now
              return ' ' + tooltipItem.parsed + '%';
            },
        }
      }
    }
  }

相关问题