Johnny
Johnny

Reputation: 125

Chart.js: Label each dataset

I've been trying to make chart.js have a label for each dataset but the first label is located underneath both datasets and the second on an empty area of the chart.

var powerChart = new Chart(powerCanvas, {
  type: "bar",
  data: {
    labels: ["Volts", "Amperes"],
    datasets: [
      {
        label: "Volts", // This bar should have this label underneath itself
        data: [24.78], // Initial value, will be overwritten
      },
      {
        label: "Amperes", // This bar should have this label underneath itself
        data: [14.51],
      },
    ],
  },
  options: {},
});

See https://jsfiddle.net/w20c3tru/2/ for what I have tried and a working example. Note: I tried to follow Chart.js Line-Chart with different Labels for each Dataset but could not see any difference.

Upvotes: 3

Views: 1287

Answers (2)

Johnny
Johnny

Reputation: 125

Finally I have it working as I want thanks to a hint by a user who separated the data in x and y sections

Code on jsFiddle

Full working example here: jsFiddle

Upvotes: 1

Zoraiz
Zoraiz

Reputation: 363

Note the comments below:

var powerChart = new Chart(powerCanvas,
    {
        type: 'bar',
        data:
        {
            labels: ['Volts', 'Amperes'],
            datasets:
                [
                    {
                        label: 'Value',       // This is actually the label that shows up when you hover over a bar
                        data: [24.78, 14.51]  // NOTE: Number of labels defined above should equal number of values here
                    },
                ]
        },
        options:
        {
        }
    }
);

Edit:

data:
{
    labels: ['Volts', 'Amperes'],
    datasets:
        [
            {
                data: [24.78, 14.51],  // Volts and amperes, respectively
                borderWidth: 1,
                borderColor: ['#0000e0', '#e00000'],  // Border colors for volts and amperes, respectively
    
            },
        ]
},

Upvotes: 3

Related Questions