TuAmigoAlejandro
TuAmigoAlejandro

Reputation: 75

Is it possible to define data attributes for each dataset value in a Chart.js chart?

Is it possible to define HTML5 data attributes for each dataset value in a Chart.js chart? The goal is to enhance the default tooltip information (e.g. X-axis value & Y-axis value) with additional information related to the target dataset value.

In the example below, a chart is displayed that plots the total number of diapers used by 6 children. When the tooltip displays, it says the name of the child and the number of diapers. I would like the tooltip to display age and gender, as well, and figured the tooltip callback could get these from data attributes attached to each dataset value.

I've reviewed the Chart.js documentation and searched online forums, like StackOverflow, without success.

var myChart = new Chart(document.getElementById('myChart'), {
    type: 'bar',
    data: {
        labels: ['Gabriel', 'Zelie', 'Santiago', 'Serafina', 'Berenice', 'Pia'],
        datasets: [{ label: 'Diapers', data: [1050, 1224, 1382, 1166, 1471, 0] }]
    },
    options: {
        legend: { display: false },
        scales: { yAxes: [{ ticks: { beginAtZero: true } }] },
        title: { display: true, text: 'Total Diapers Used' },
        tooltips: {
            titleFontSize: 18,
            callbacks: {
                label: function(tooltipItem, data) {
                    var defaultLabel = data.datasets[tooltipItem.datasetIndex].label + ': ' + tooltipItem.yLabel;
                    var age = "Age: <age>";
                    var gender = "Gender: <gender>";
                    var labels = [defaultLabel, age, gender];
                    return labels;
                }
            }
        }
    }
});
</script>

Example Chart w/ Tooltip Showing Additional Info

Upvotes: 1

Views: 466

Answers (1)

HeadhunterKev
HeadhunterKev

Reputation: 1788

It depends how you structure your data. In my example I made an object that contains all the data.

let dataObject = {
  Gabriel: {
    diapers: 40,
    age: 4
  }, 
  // Same structure here...
  Zelie: {...}, 
  Santiago: {...}, 
  Serafina: {...}, 
  Berenice: {...}, 
  Pia: {...}
}

This way you can easily access your data in your tooltip with

tooltips: {
  callbacks: {
    label: function(tooltipItem, data){
      return ['Name: '+tooltipItem.label, 'Diapers: '+tooltipItem.value, 'Age: '+dataObject[tooltipItem.label].age]
    }
  }
}

You should get all the information you need in the jsbin.

https://jsbin.com/qiyeyohavo/1/edit?html,js,output

Upvotes: 1

Related Questions