【问题标题】:Chart.js v3.60 - Add % symbol to the end of the tooltip label on a doughnut chart?Chart.js v3.60 - 在圆环图的工具提示标签末尾添加 % 符号?
【发布时间】:2022-06-21 04:13:06
【问题描述】:

我需要如何修改下面的代码,以便在工具提示值的末尾添加一个 % 符号?

我尝试了很多来自不同帖子的解决方案,但它们似乎都是 v2.0 解决方案。我不确定在回调行中写什么。

const ctx = document.getElementById('myChart');
const myChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
        datasets: [{
            data: [12, 19, 3, 5, 2],
            backgroundColor: [
                '#b59671',
                '#c7ba53',
                '#7da35a',
                '#4c77ba',
                '#000000'
            ],
            borderColor: [
                '#b59671',
                '#c7ba53',
                '#7da35a',
                '#4c77ba',
                '#000000'
            ],
            borderWidth: 1,
        }]
    },
    options: {
        cutout: 300,
        hoverOffset: 8,
        plugins: {
            tooltip: {
                displayColors: false,
                callbacks: {

                }
            }
        }
    }
});

【问题讨论】:

标签: charts chart.js


【解决方案1】:

这是一个工作示例:

const ctx = document.getElementById('myChart');
const myChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
        datasets: [{
            data: [0.12, 0.19, 0.3, 0.5, 0.2],
            backgroundColor: [
                '#b59671',
                '#c7ba53',
                '#7da35a',
                '#4c77ba',
                '#000000'
            ],
            borderColor: [
                '#b59671',
                '#c7ba53',
                '#7da35a',
                '#4c77ba',
                '#000000'
            ],
            borderWidth: 1,
        }]
    },
    options: {
        cutout: 300,
        hoverOffset: 8,
        plugins: {
            tooltip: {
                displayColors: false,
                callbacks: {
                    label: function(context) {
                        let label = new Intl.NumberFormat('en-US', {
                            style: 'percent',
                            minimumFractionDigits: 0,
                            maximumFractionDigits: 0
                        }).format(context.formattedValue);
                        return label;
                    },
                    title: function(context) {
                      let title = context[0].label;
                      return title;
                    }
                },
            }
        }
    }
});

【讨论】:

    【解决方案2】:

    一个简短的解决方案就是在{data.formattedValue} 位之后添加%

    plugins: {
        tooltip: {
            callbacks: {label: data => `${data.formattedValue}%` }}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-22
      • 1970-01-01
      • 2018-12-05
      • 2021-04-22
      • 1970-01-01
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      相关资源
      最近更新 更多