Chartjs-Chartjs: bars smaller than actual column, tooltip doesn't display

2๐Ÿ‘

โœ…

You can set the intersect property to false to always get the tooltip without needing to intersect the bar exactly:

var options = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderWidth: 1
    }]
  },
  options: {
    plugins: {
      tooltip: {
        intersect: false
      }
    }
  }
}

var 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.5.0/chart.js"></script>
</body>

0๐Ÿ‘

You can make your own tooltip by editing the callbacks, i had to get the nearest values around my cursor, from all datasets, on my line chart. this works for me on Chartjs 2.9.3:

tooltips: {
    mode: "x",
    position: "nearest",
    intersect: false,
    callbacks: {
        beforeBody: function(tooltipItems, allData) {
            let x = tooltipItems[0].x; // get x coordinate

            let datasets = allData.datasets; // datasets
    
            let values = [];
            for (i in datasets) {
                let dataset = datasets[i]; 

                let meta = this._chart.getDatasetMeta(i); // dataset metadata
                let xScale = this._chart.scales[meta.xAxisID]; // dataset's x axis
                let xValue = xScale.getValueForPixel(x); // we get the x value on the x axis with x coordinate

                let data = dataset.data // data

                // search data for the first value with a bigger x value
                let index = data.findIndex(function(o) { 
                    return o.x >= xValue; 
                });

                let value = data[index]; // this is our nearest value

                // format label
                if (isNaN(value.ymax)) {
                    values.push(`${dataset.label}: ${value.y}\n`);
                } else {
                    values.push(`${dataset.label}: ${value.y}, min: ${value.ymin}, max: ${value.ymax}\n`)
                }
            }

            return values.join(""); // return label
        },

        label: function() { // this needs to be empty

        },
    }
},

Leave a comment