如何正确使用 chartjs 数据标签插件 [英] How to properly use the chartjs datalabels plugin

查看:33
本文介绍了如何正确使用 chartjs 数据标签插件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Chart.js to create a bar char, I have to display the percentage on each bar, so I found the chartjs-plugin-datalabels, but I can't make it work, the documentation and the examples are not clear for me.

这就是我得到的:

HTML:

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

Javascript:

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();

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

Supposedly, from what I get, the "plugin" inside option is the one that let the values to be display, but as I shown in my code above, doesn't work for me, surely I'm missing something but I don't know what, can somebody help me?

谢谢.

小提琴:

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

推荐答案

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

It was because of the version of the Chartjs I was using, this plugin requieres 2.7.0 or later.

这篇关于如何正确使用 chartjs 数据标签插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆