【问题标题】:How to properly use the chartjs datalabels plugin如何正确使用 chartjs 数据标签插件
【发布时间】:2018-03-20 19:33:29
【问题描述】:

我正在使用 Chart.js 创建一个条形字符,我必须在每个条形上显示百分比,所以我找到了 chartjs-plugin-datalabels,但我无法使其工作,文档和示例都没有对我来说清楚。

这就是我得到的:

HTML:

<canvas id="bar-chart" width="800" height="450"></canvas>

Javascript:

// Bar chart

var valuedata= [2478,5267,734,784,433];
var valuelabel=["Africa", "Asia", "Europe", "Latin America", "North America"];


var myBarChart = new Chart(document.getElementById("bar-chart"), {
    type: 'bar',
    data: {
      labels: valuelabel,
      datasets: [
        {
          label: "Population (millions)",
          backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
          data: valuedata,

        }
      ]
    },
    options: {
      legend: { display: false },
      title: {
        display: true,
        text: 'Predicted world population (millions) in 2050'
      },
      scales: {
    xAxes: [{
                gridLines: {
                    display:false
                }
            }],
    yAxes: [{
                gridLines: {
                    display:false,
                    drawBorder: false
                },
                ticks: {
                display: false
            }
            }]
    },
      plugins: {
                    datalabels: {
                        color: 'white',
                        display: function(context) {
                            console.log("Algo: "+context);
                            return context.dataset.data[context.dataIndex] > 15;
                        },
                        font: {
                            weight: 'bold'
                        },
                        formatter: function(value, context) {
                        return context.dataIndex + ': ' + Math.round(value*100) + '%';
                    }
                    }
                }
    }
});

myBarChart.update();

据我所知,里面的“插件”选项是让值显示的选项,但正如我在上面的代码中显示的那样,对我不起作用,我肯定错过了一些东西,但是我不知道是什么,有人可以帮帮我吗?

谢谢。

小提琴:

https://jsfiddle.net/s64bq4sw/16/

【问题讨论】:

    标签: plugins chart.js


    【解决方案1】:

    因为我使用的 Chartjs 版本,这个插件需要 2.7.0 或更高版本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      • 2021-04-04
      相关资源
      最近更新 更多