How to change the position of the tooltip for the Bar type chart in Chart.Js

3.5k Views Asked by At

By default Chart.js will display the tool tip at the top of the bar for the bar type of charts. I am trying to change the default position of the tooltip from the top to the center of the bar.

Which is some thing similar to as shown in the below image.

Appreciate help on this, Thank you.

enter image description here

1

There are 1 best solutions below

0
uminder On

You need to define a new tooltip position mode as follows:

Chart.Tooltip.positioners.middle = elements => {
  let model = elements[0]._model;
  return {
    x: model.x,
    y: (model.base + model.y) / 2
  };
};

Further you have to define tooltips within the chart options as follows:

tooltips: {
  position: 'middle',  // must match the positioner function name defined above
  yAlign: null,        // to get rid of the pointer
  xAlign: 'center'
}

Please take a look at below runnable code snippet and see how it works:

Chart.Tooltip.positioners.middle = elements => {
  let model = elements[0]._model;
  return {
    x: model.x,
    y: (model.base + model.y) / 2
  };
};

new Chart(document.getElementById("chart"), {
  type: "bar",
  data: {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
      label: "My Dataset",
      data: [65, 59, 80, 81, 56, 55, 40],
      backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(201, 203, 207, 0.2)"],
      borderColor: ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(54, 162, 235)", "rgb(153, 102, 255)", "rgb(201, 203, 207)"],
      borderWidth: 1
    }]
  },
  options: {
    tooltips: {
      position: 'middle',  
      yAlign: null,
      xAlign: 'center'
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="chart" height="90"></canvas>

Display the resulting chart in full page mode if the tooltips don't show up in embedded mode.