【问题标题】:Chartjs tooltip anchor point position on bar chartsChartjs 工具提示锚点在条形图上的位置
【发布时间】:2019-07-15 23:24:01
【问题描述】:

我有一个使用 Chartjs 的条形图,具有固定的 y 轴最大值。有时数据可能会超过最大值,但悬停工具提示始终固定在条形顶部,因此无法看到。工具提示的 position 选项对我来说真的不起作用。

那么,有没有办法在栏的底部显示工具提示?或者它可以像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>

【问题讨论】:

  • 似乎 SO 的 sn-p 存在错误,例如 this one。请转到整页。

标签: javascript chart.js


【解决方案1】:

可以通过向 Chart.Tooltip.positioners 地图添加功能来定义新模式。 您可以像在 chartjs 的 Doc 中一样创建自定义定位:

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

    /* ... */

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

您需要在渲染图表时将自定义函数设置为您的选项:

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;
              }
            }
          }

看我完整的Fiddle 示例。

【讨论】:

  • 像魅力一样工作!一个微不足道的后续问题,工具提示在您的小提琴中跟随鼠标光标移动,但在我自己的开发环境中没有(相同的图表选项,相同的浏览器)。可能的原因是什么?
  • 在你的 DevTools 中显示一些错误?你清除浏览器缓存了吗?您能否提供有关您的开发环境的更多详细信息?
  • @EdiCarlos,你能用 ng2-charts 分享同一个 Angular 演示吗?
猜你喜欢
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
相关资源
最近更新 更多