【问题标题】:Adding custom text to Bar Chart label values using Chart.js使用 Chart.js 将自定义文本添加到条形图标签值
【发布时间】:2018-10-12 11:41:46
【问题描述】:

我正在使用 Chart.js 插件来显示条形图,我得到的输出如下:

我的问题是,如何在将值渲染到栏后添加自定义文本?例如,In Jan,value 显示为 56。我想在其旁边添加 % increased/decrease 信息(即 56 [115 %]),该怎么做?

这是我的代码

    window.chartHeadcount = new Chart(document.getElementById("barChartHeadcount"), {
        type: 'bar',
        data: {
            labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            datasets: [{
                label: 'Billed',
                backgroundColor: 'rgb(0, 197, 106)',
                data: billedHeadCount
            }, {
                label: 'Unbilled',
                backgroundColor: 'rgb(255, 114, 107)',
                data: unBilledHeadCount
            }]
        },
        options: {
            title: {
                display: true,
                text: 'Community Headcount - ' + Options.Globals.Year
            },
            tooltips: {
                mode: 'index',
                intersect: false
            },
            responsive: true,
            scales: {
                xAxes: [{
                    stacked: false
                }],
                yAxes: [{
                    stacked: false
                }]
            }
        }
    });

【问题讨论】:

    标签: jquery label chart.js


    【解决方案1】:

    您可以使用插件 chartjs-datalabels 并设置 formatter 属性来设置您的自定义标签。

    创建了一个小提琴供您参考 -> http://jsfiddle.net/upmth2cq/1/

    希望能帮助到你!

    new Chart(document.getElementById("barChartHeadcount"), {
      type: 'bar',
      data: {
        labels: ['Jan', 'Feb', 'Mar'],
        datasets: [{
          label: 'Billed',
          backgroundColor: 'rgb(0, 197, 106)',
          data: [56, 63, 67]
        }, {
          label: 'Unbilled',
          backgroundColor: 'rgb(255, 114, 107)',
          data: [1, 2, 3]
        }]
      },
      options: {
        title: {
          display: true,
          text: 'Community Headcount'
        },
        tooltips: {
          mode: 'index',
          intersect: false
        },
        responsive: true,
        scales: {
          xAxes: [{
            stacked: false
          }],
          yAxes: [{
            stacked: false
          }]
        },
        plugins: {
          datalabels: {
            align: 'end',
            anchor: 'end',
            backgroundColor: function(context) {
              return context.dataset.backgroundColor;
            },
            borderRadius: 4,
            color: 'white',
            formatter: function(value){
                return value + ' (100%) ';
            }
          }
        }
      }
    });
    

    【讨论】:

    • 我正在使用它。但是,是否可以从另一个数组中获取它?而不是硬编码值
    • 是的,您需要在函数内部有自己的逻辑,并将硬编码值替换为计算值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2011-01-09
    • 2021-03-27
    • 2017-02-10
    • 2014-07-04
    • 1970-01-01
    • 2016-04-18
    相关资源
    最近更新 更多