Chartjs-Chartjs datalabels is not showing the labels on the bar chart

1👍

You forgot to initialize the plugin!

Add this:

Chart.register(ChartDataLabels);

Some additional info / improvements

  • The color of the datalabels should be inside the labels.value object. I’ve moved that so the lables are the correct color (#FFCE56)

  • The color on the dataset should be backgroundColor, changed that as well

  • I’ve implemented a formatter on the label with the use of this question on how to apply thousand-seperators, just to make it more readable (again).

    formatter: n => numberWithCommas(n),
    

Updated Snippet
const data = [{"date": "2023-02-23", "subscribers": 1208123 }, {"date": "2023-02-22", "subscribers": 1045338 }, {"date": "2023-02-21", "subscribers": 1043130 }, {"date": "2023-02-20", "subscribers": 1248035 }, {"date": "2023-02-19", "subscribers": 1243734 }, {"date": "2023-02-18", "subscribers": 1240317 }, {"date": "2023-02-17", "subscribers": 1033439 }, {"date": "2023-02-16", "subscribers": 974864 } ]; 
const chart_label = "Number of subscribers";
  
Chart.register(ChartDataLabels); // Enable plugin

const chart_canvas = document
      .getElementById("number_of_messages_delivered")
      .getContext("2d");

push_messages_chart = new Chart(chart_canvas, {
    type: "bar",
    options: {
        animation: true,
        plugins: {
            // Change options for ALL labels of THIS CHART
            datalabels: {
                formatter: n => numberWithCommas(n),
                display: true, // Set to true to display the labels
                labels: {
                    value: {
                        color: "#FFCE56"
                    }
                } 
            }
        },
    },
    data: {
        labels: data.map((row) => row.date),
        datasets: [
            {
                label: chart_label,
                data: data.map((row) => row.subscribers),
                backgroundColor: "#FE777B",
            },
        ],
    },
});

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.0.0/dist/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.2.0/chartjs-plugin-datalabels.min.js"></script>
<canvas id="number_of_messages_delivered"></canvas>

Leave a comment