How can I display the xAxes and yAxes data in the tooltip, Chart JS?

Viewed 135

I am trying to achieve the Tooltip shown below in the first image. Inside of the tooltip I need to display the yAxes and xAxes data. The chart.js version I am using is 3.7.0

My tooltip looks like this:

enter image description here

The tooltip that I am trying copy:

enter image description here

The chart.js documentation is quite hard for me to understand. Is there any guru that can explain to me.

Question: Why is my tooltip returning the yAxes data, that I return as a variable(label) as undefined?

Are there any other options I can use to make my chart look like the chart in the second picture?

My Code:

 tooltip: {
   displayColors: false,
   backgroundColor: 'rgba(45,132,180,0.8)',
   bodyFontColor: 'rgb(255,255,255)',
   callbacks: {
     title: function(item, everything){
       return;
     },
     label: function(item, everything){
       //console.log(item);
       //console.log(everything);

       let first = item.yLabel;
       let second = item.xLabel;

       let label = first + ' ppm';
       return label;
     }
   }
 }

Thank you in advance for your time and efforts, please help me figure out what am I doing wrong!

1 Answers

yLabel and xLabel dont exist anymore on the tooltip, they are V2 syntax. You can just axess the y object in the parsed section to get the y value. Then you can use the afterBody callback to show the x label like so:

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderColor: 'pink'
    }]
  },
  options: {
    plugins: {
      tooltip: {
        displayColors: false,
        backgroundColor: 'rgba(45,132,180,0.8)',
        bodyFontColor: 'rgb(255,255,255)',
        callbacks: {
          title: () => {
            return
          },
          label: (ttItem) => (`${ttItem.parsed.y} ppm`),
          afterBody: (ttItems) => (ttItems[0].label)
        }
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>

Related