Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

javascript - How to show data values or index labels in ChartJs (Latest Version)

How to show data values or index labels in ChartJs (Latest Version) as in the below image:

enter image description here

I am using the ChartJs to display charts in my React Project. Everything is working fine, except this.

I found an answer in stackoverflow (https://stackoverflow.com/a/31632707), But it uses an old version of chartjs and is not working on the one which I am using.

My ChartJs Code:

var ctx = document.getElementById("myChart");

var BarChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Jan","Feb","March"],
        datasets: [{
            label: "Chart Data",
            data: [10,20,15],
            backgroundColor: "red",
            borderColor: "green",
            borderWidth: 1
        }]
    },
    options: {
        legend: {
            display: false
        },
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }],
            xAxes: [{
                ticks: {
                    maxRotation: 180
                }
            }]
        }
    }
});

I tried adding it using the function: ctx.fillText(bar.value, bar.x, bar.y - 5);, But its showing .fillText is not a function

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Finally I got it working.

Used the following code in the onComplete() function:

animation: {
    onComplete: function () {
        var ctx = this.chart.ctx;
        ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
        ctx.fillStyle = "black";
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';

        this.data.datasets.forEach(function (dataset)
        {
            for (var i = 0; i < dataset.data.length; i++) {
                for(var key in dataset._meta)
                {
                    var model = dataset._meta[key].data[i]._model;
                    ctx.fillText(dataset.data[i], model.x, model.y - 5);
                }
            }
        });
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...