Chartjs-ChartJS hover/tooltips: selecting the correct points in the datasets based on x-value

0👍

Well, in the end I had to modify the ChartJS source code to achieve this. Fortunately, it wasn’t too hard. All I had to do was add this function to the core.interaction.js file:

function xPositionMode(chart, e, options) {
    var position = getRelativePosition(e, chart);
    // Default axis for index mode is 'x' to match old behaviour
    options.axis = options.axis || 'x';
    var distanceMetric = getDistanceMetricForAxis(options.axis);
    var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
    var elements = [];
    if (!items.length) {
        return [];
    }

    const findClosestByX = function(array, element) {
        let minDiff = -1;
        let ans;
        for (let i = 0; i < array.length; i++) {
          var m = Math.abs(element._view.x - array[i]._view.x);
          if (minDiff === -1 || m < minDiff) {
            minDiff = m;
            ans = array[i];
          }
        }
        return ans;
    }

    chart._getSortedVisibleDatasetMetas().forEach(function(meta) {
        var element = findClosestByX(meta.data, items[0]);

        // don't count items that are skipped (null data)
        if (element && !element._view.skip) {
            elements.push(element);
        }
    });

    return elements;
}

This is basically a modified version of the indexMode function present in the same file, but instead of searching items by their index in the dataset it searches the closest items by their horizontal position on the canvas (see the findClosestByX inner function for the search algorithm)

To make this usable, you also have to add the new mode in the list of exports (in the same file):

module.exports = {
    // Helper function for different modes
    modes: {
        xPosition: xPositionMode,
        //Rest of the original code...
    }
}

Once this is done, recompile the ChartJS library and use it instead of the original one. Now you can use the new mode like this:

options: {
    hover: {
        mode: 'xPosition',
        intersect: false
    }
    //other options...
}

Note: all code in this answer refers to the 2.9.4 version of the ChartJS library, it might not work the same for 3.x versions.

1👍

If someone has the same problem in a more recent version (like 3.7.0), you can just modify the interaction mode: instead of ‘index’, use this:

options: {
        interaction: {
            intersect: false,
            mode: 'nearest',
            axis: 'x'      
        },
}

found on the docs

Leave a comment