[Chartjs]-How do I get a different label for each bar in a bar chart in ChartJS?

2👍

If your aim is to take the values from an array and have them appear along the bottom of the bar chart so that each array value is the label for a bar then you need to set the data.labels value, not the data.datasets.label value.

For example, this basic chart is taken from the Chart.js documentation for bar chart data structure and shows how to use an array of month names to label the bars. Notice that the label bars go into the data.labels node.

var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            borderWidth: 1,
            hoverBackgroundColor: "rgba(255,99,132,0.4)",
            hoverBorderColor: "rgba(255,99,132,1)",
            data: [65, 59, 80, 81, 56, 55, 40],
        }
    ]
};

If you programmatically create an array with one label for each point of data then it might look something like this:

var chartConfig = {};

for (score = 0; score < maxScore; ++score) {
    chartConfig.scoreLabels[score] = score;
    chartConfig.scoreData[score] = howManyAchievedScore(score);
}

var data = {
    labels: chartConfig.scoreLabels,
    datasets: [
        {
            label: "Number of players who achieved score",
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            borderWidth: 1,
            hoverBackgroundColor: "rgba(255,99,132,0.4)",
            hoverBorderColor: "rgba(255,99,132,1)",
            data: chartConfig.scoreData,
        }
    ]
};

You don’t have to create the labels and data values inside a single object, but it’s usually tidier if you can group your chart configuration data into one object so that you can pass it from one function to another with one parameter.

The data.datasets.label value does something different, providing text which appears in the chart legend and in tooltips which appear when you hover over a bar.

Leave a comment