如何在 Chart.js 上显示数据值

2022-01-22 00:00:00 javascript chart.js

是否可以使用


HTML

脚本

var chartData = {标签:[一月"、二月"、三月"、四月"、五月"、六月"],数据集:[{填充颜​​色:#79D1CF",strokeColor: "#79D1CF",数据:[60、80、81、56、55、40]}]};var ctx = document.getElementById(myChart1").getContext(2d");var myLine = new Chart(ctx).Line(chartData, {显示工具提示:假,onAnimationComplete: 函数 () {var ctx = this.chart.ctx;ctx.font = this.scale.font;ctx.fillStyle = this.scale.textColorctx.textAlign = "中心";ctx.textBaseline = 底部";this.datasets.forEach(函数(数据集){dataset.points.forEach(函数(点){ctx.fillText(points.value, points.x, points.y - 10);});})}});var ctx = document.getElementById(myChart2").getContext(2d");var myBar = new Chart(ctx).Bar(chartData, {显示工具提示:假,onAnimationComplete: 函数 () {var ctx = this.chart.ctx;ctx.font = this.scale.font;ctx.fillStyle = this.scale.textColorctx.textAlign = "中心";ctx.textBaseline = 底部";this.datasets.forEach(函数(数据集){dataset.bars.forEach(function (bar) {ctx.fillText(bar.value, bar.x, bar.y - 5);});})}});


小提琴 - http://jsfiddle.net/uh9vw0ao/

Is it possible using Chart.js to display data values?

I want to print the graph.

Thanks for any advice..

解决方案

There is an official plugin for Chart.js 2.7.0+ to do this: Datalabels

Otherwise, you can loop through the points / bars onAnimationComplete and display the values


Preview


HTML

<canvas id="myChart1" height="300" width="500"></canvas>
<canvas id="myChart2" height="300" width="500"></canvas>

Script

var chartData = {
    labels: ["January", "February", "March", "April", "May", "June"],
    datasets: [
        {
            fillColor: "#79D1CF",
            strokeColor: "#79D1CF",
            data: [60, 80, 81, 56, 55, 40]
        }
    ]
};

var ctx = document.getElementById("myChart1").getContext("2d");
var myLine = new Chart(ctx).Line(chartData, {
    showTooltips: false,
    onAnimationComplete: function () {

        var ctx = this.chart.ctx;
        ctx.font = this.scale.font;
        ctx.fillStyle = this.scale.textColor
        ctx.textAlign = "center";
        ctx.textBaseline = "bottom";

        this.datasets.forEach(function (dataset) {
            dataset.points.forEach(function (points) {
                ctx.fillText(points.value, points.x, points.y - 10);
            });
        })
    }
});

var ctx = document.getElementById("myChart2").getContext("2d");
var myBar = new Chart(ctx).Bar(chartData, {
    showTooltips: false,
    onAnimationComplete: function () {

        var ctx = this.chart.ctx;
        ctx.font = this.scale.font;
        ctx.fillStyle = this.scale.textColor
        ctx.textAlign = "center";
        ctx.textBaseline = "bottom";

        this.datasets.forEach(function (dataset) {
            dataset.bars.forEach(function (bar) {
                ctx.fillText(bar.value, bar.x, bar.y - 5);
            });
        })
    }
});


Fiddle - http://jsfiddle.net/uh9vw0ao/

相关文章