简体   繁体   中英

Chartjs tooltip anchor point position on bar charts

I have a bar chart using Chartjs, with a fixed y-axis max. Sometimes the data can exceed the max, but the hover tooltip is always anchored to the top of the bars so it cannot be seen. The tooltips' position option does not really work for me.

So, is there a way to display the tooltip at the bottom of the bars? Or can it follow the hovering mouse cursor like canvasjs ?

 var ctx = document.getElementById("chart").getContext("2d"); var barChart = new Chart(ctx, { type: 'bar', options: { scales: { yAxes: [{ display: true, ticks: { min: 0, max: 120 }, }], }, tooltips: { // position: 'nearest', position: 'average', }, legend: { display: false } }, data: { labels: ["A", "B", "C", "D"], datasets: [{ label: "Data Set 1", backgroundColor: [ '#44b2d7', '#44b2d7', '#44b2d7', '#44b2d7', ], borderColor: [ '#44b2d7', '#44b2d7', '#44b2d7', '#44b2d7' ], borderWidth: 0, data: [131, 65, 165, 85] }] } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script> <canvas id="chart" height="180"></canvas> 

New modes can be defined by adding functions to the Chart.Tooltip.positioners map. You can create your custom postitioning like in the Doc of chartjs:

    Chart.Tooltip.positioners.custom = function(elements, eventPosition) {
    /** @type {Chart.Tooltip} */
    var tooltip = this;

    /* ... */

    return {
        x: eventPosition.x,
        y: eventPosition.y
    };
}

you need to set your custom function into your options when rendering your chart:

tooltips: { 
            position : 'custom',   //<-- important same name as your function above      
            callbacks: {
              label: function(tooltipItem, data) {
               var label = Math.floor(tooltipItem.yLabel*100)/100+" "+data.datasets[tooltipItem.datasetIndex].label;
               return label;
              }
            }
          }

Look my full Fiddle example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM