How to show data values or index labels in ChartJs (Latest Version)
Asked Answered
L

2

5

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

Literature answered 13/7, 2016 at 6:55 Comment(7)
Is ctx defined when you call this? .fillText() is a canvas function and should be there. Maybe it is just your declaration. I think it should be var ctx = document.getElementById("myChart").getContext("2d");Antitrust
Yes. I console logged it in the console. And it works fine.Literature
Let me check that by adding .getContext("2d")Literature
Now the .fillText() is working fine. But it shows this.datasets as undefined. But console.log(this) => {chart: t, config: Object, options: Object, id: 0, titleBlock: n…} But this object does not contain the datasets objectLiterature
You should find your dataset in chart.config.dataAntitrust
Yes. I already tried that, but the chart.config.data does not contain the bars array. Also it does not contain the x and y valuesLiterature
@Antitrust : is there any way to get the datasets x and y values?Literature
L
9

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);
                }
            }
        });
    }
}
Literature answered 13/7, 2016 at 11:45 Comment(0)
A
3

Got it to work after some researching.

You have to set it after in the onComplete event of the animation. The x, y values of the bars are stored in the model of the children (point, line, bar, whatever)

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

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

Just the structure changed a little bit.

You can see it in this working JSFiddle

Antitrust answered 13/7, 2016 at 10:38 Comment(4)
Again got with an error :( var model = dataset._meta[0].dataset._children[i]._model; In this statement I am getting an error saying Cannot read property '_children' of null For me dataset._meta[0].dataset is nullLiterature
KRONWALLED: Thank you for your guidance :)Literature
Hi there, Can someone guide me how to do this in react?Forswear
Getting this error dataset._meta[0].dataset is null. Any idea?Kaiserism

© 2022 - 2024 — McMap. All rights reserved.