Chartjs-Chart.js โ€“ barchart โ€“ plugin labels

1๐Ÿ‘

โœ…

You can sum each week by accessing datasets by context and then use reduce function. Datalabel position can be set by Chart.defaults.global.plugins.datalabels before you create the chart. Using anchor end, align end will put the label on top of the bar.

    Chart.defaults.global.plugins.datalabels.anchor = 'end';
    Chart.defaults.global.plugins.datalabels.align = 'end';

    var ctx = document.getElementById("myBarChart");
    var myLineChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ["WEEK1", "WEEK2", "WEEK3", "WEEK4", "WEEK5"
            ],
            datasets: [{
            label: "AMPDS ",
            backgroundColor: "#dc3545",
            borderColor: "rgba(2,117,216,1)",
            data: [20,24,30,36,10
            ],
            },
            {
            label: "VISITE",
            backgroundColor: "#ffc107",
            borderColor: "rgba(2,117,216,1)",
            data: [5,5,1,6,5
            ],
            },
            {
            label: "ABSTRICH",
            backgroundColor: "rgba(2,117,216,1)",
            borderColor: "rgba(2,117,216,1)",
            data: [10,12,15,18,20
            
            ],
            }
            
            ],
        },
        options: {
            plugins: {
                datalabels: {
                    formatter: (value, ctx) => {
                        const { dataIndex } = ctx
                        let datasets = ctx.chart.data.datasets
                        let max = datasets.reduce((a,c)=>a+c.data[dataIndex],0)
                        return Math.round(value * 100 / max);;
                    },
                }
            },
            scales: {
            xAxes: [{
                time: {
                unit: 'month'
                },
                gridLines: {
                display: false
                },
                ticks: {
                maxTicksLimit: 6
                }
            }],
            yAxes: [{
                    ticks: {
                    min: 0,
                    max: 55,
                    maxTicksLimit: 5
                    },
                    gridLines: {
                    display: true
                    }
                }],
            },
            legend: {
                display: false
            }
        }
    });

Leave a comment