Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js - Hover labels to display data for all data points on x-axis

Tags:

chart.js

I have a graph with multiple data points / lines. Currently, if you hover near a data point, it will display the label/value for that point.

What I'd like is the following: when you hover anywhere on the chart, it will display the labels + values for all data points at that x-value simultaneously in a single label.

For example, let's take the given datasets:

Date (x-labels): ['Jan 01','Jan 02','Jan 03']
Apples Sold: [3,5,1]
Oranges Sold: [0,10,2]
Gallons of Milk Sold: [5,7,4]

When you hover over the middle of the graph, above the 'Jan 02' vertical space, the label should display:

Jan 02
-----------------------
Apples Sold: 5
Oranges Sold: 10
Gallons of Milk Sold: 7

Is there a simple way to accomplish this?

Thanks.

like image 241
Dan Avatar asked Mar 01 '18 22:03

Dan


1 Answers

Is there a simple way to accomplish this?

YES !! There is a quite straightforward way to accomplish this. If you would have read the documentation, you could have found that pretty easily.

Anyway, basically you need to set the tooltips mode to index in your chart options, in order to accomplish the behavior you want.

...
options: {
   tooltips: {
      mode: 'index'
   }
}
...

Additionally, you probably want to set the following:

...
options: {
   tooltips: {
      mode: 'index',
      intersect: false
   },
   hover: {
      mode: 'index',
      intersect: false
   }
}
...

This will make it so all of the expected hover/label interactions will occur when hovering anywhere on the graph at the nearest x-value.

From the Documentation :

# index
Finds item at the same index. If the intersect setting is true, the first intersecting item is used to determine the index in the data. If intersect false the nearest item, in the x direction, is used to determine the index.

Here is a working example :

var ctx = document.getElementById('canvas').getContext('2d');
var chart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ['Jan 01', 'Jan 02', 'Jan 03'],
      datasets: [{
         label: 'Apples Sold',
         data: [3, 5, 1],
         borderColor: 'rgba(255, 99, 132, 0.8)',
         fill: false
      }, {
         label: 'Oranges Sold',
         data: [0, 10, 2],
         borderColor: 'rgba(255, 206, 86, 0.8)',
         fill: false
      }, {
         label: 'Gallons of Milk Sold',
         data: [5, 7, 4],
         borderColor: 'rgba(54, 162, 235, 0.8)',
         fill: false
      }]
   },
   options: {
      tooltips: {
         mode: 'index',
         intersect: false
      },
      hover: {
         mode: 'index',
         intersect: false
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="canvas"></canvas>
like image 80
Neeraj Avatar answered Oct 07 '22 05:10

Neeraj