Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to combine two Y axes into a single tooltip with ChartJS 2?

Suppose I have two Y axes, labeled "foo" and "bar". These axes correspond to points along the same interval, e.g. weekly aggregates of foos and bars in say the last 12 weeks. Ideally you would mouseover one of these points along the line chart and the tooltip would display the data of the week in question for both foo and bar; this is how it works if you don't have more than one Y axes. In practice you have you mouseover the individual point to see only the data for that specific point.

For clarity, this is what my chart options look like:

const CHART_OPTIONS = {
  scales:
  {
    xAxes: [{
      ticks: {
        display: false,
      },
    }],
    yAxes: [
      {
        type: 'linear',
        id: 'y-axis-0',
        display: false,
        position: 'left',
      },
      {
        type: 'linear',
        id: 'y-axis-1',
        display: false,
        position: 'right',
      },
    ],
  },
};

The chart data specifies a yAxisID of y-axis-0 and y-axis-1 respectively.

For those who haven't seen a chart with two Y axes, I've prepared a simple example.

So my question is if this can be done with Chart.js 2?

like image 351
maxcountryman Avatar asked Feb 06 '23 16:02

maxcountryman


1 Answers

References:

Chartjs Docs: Tooltip Configuration - Interaction Modes

mode : 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 is used to determine the index.

Update the chart options to include the tooltips configurations. Set the mode to index

tooltips : {
    mode : 'index'
},

The updated options would look like this.

const CHART_OPTIONS = {
  tooltips : {
    mode : 'index'
  },
  scales:
  {
    xAxes: [{
      ticks: {
        display: false,
      },
    }],
    yAxes: [
      {
        type: 'linear',
        id: 'y-axis-0',
        display: false,
        position: 'left',
      },
      {
        type: 'linear',
        id: 'y-axis-1',
        display: false,
        position: 'right',
      },
    ],
  },
};

Check updated sample which include tooltips mode set to index

like image 134
Nkosi Avatar answered Mar 02 '23 00:03

Nkosi