ChartsJS get value of Data/Dataset Label for Tooltip

Viewed 1465

I'm very new to ChartJS (and JS in general) and couldn't find a fitting answer for my problem anywhere online.

I'm trying to customize the tooltips in my Bubblechart to fit format:

Dataset Label x.value: X y.value: X

For x and y values I'm fine. But I can't get the Headline I want.

For the Title I'm curently trying

            tooltips: {
        callbacks: {
            title: function(tooltipItems, data) {
                    return data.datasets[tooltipItems[0].datasetIndex].label;
                }               
            }               
        }

But this returns the entire array of all Labels for every Bubble. I guess this is due to how I populated the Labels.

    data = {
 labels: LabelArray,
 datasets: [{
   label: LabelArray,
       data: chartData
   }]};

I have labels under data and datasets because it didn't work with labels under datasets.

Any information on how to solve this is highly appreciated!

Sample Data of my Arrays:

    chartData: 
    0: Object { x: "2786", y: "12.4", r: "15.32" }
    1: Object { x: "4998", y: "23.7", r: "52.46" }​
    2: Object { x: "719", y: "20.4", r: "6.5" }​ 
    3: Object { x: "3649", y: "15.9", r: "25.73" }

    LabelArray: 
    0: "A"​ 
    1: "B"​ 
    2: "C"​ 
    3: "D"

Best regards, David

1 Answers

Based on the sampleData you posted above this is what you're passing to your tooltip in data. The problem is that you're passing an array to label when it is supposed to be a string - documentation.

data = {
    labels: ["A", "B", "C", "D"],
    datasets: [
        {
        label: ["A", "B", "C", "D"],
        data: [
                { x: "2786", y: "12.4", r: "15.32" }​,
                { x: "4998", y: "23.7", r: "52.46" }​,
                { x: "719", y: "20.4", r: "6.5" }​,
                { x: "3649", y: "15.9", r: "25.73" }
            ]
      }
  ]
};

If you're trying to pass multiple data points with different labels then you will need to breakout your datasets into an array of objects like so.

data = {
    datasets: [
      {
        label: "A",
        data: [{ x: "2786", y: "12.4", r: "15.32" }​]
      },
      {
        label: "B",
        data: [{ x: "4998", y: "23.7", r: "52.46" }​]
      },
      {
        label: "C",
        data: [{ x: "719", y: "20.4", r: "6.5" }​]
      },
      {
        label: "D",
        data: [{ x: "3649", y: "15.9", r: "25.73" }]
      }
  ]
};

If you must save your labels to an array then you need to extract which label you need when building your chart data. Something like this should work...

dynamicData =[
  { x: "2786", y: "12.4", r: "15.32" }​,
  { x: "4998", y: "23.7", r: "52.46" }​
];
labelArray = ["A","B","C","D"];
parsedData = [];

for(let i = 0; i < dynamicData.length; i++) {
    parsedData.push({
      label: labelArray[i],
      data: [dynamicData[i]]
    });
}

data = {
    datasets: parsedData
};
Related