Chart.js 2.7.0分组的水平条形图,如何获取工具提示以显示一个条形而不是整个组的数据?

只是看看

这是一个分组的水平条形图:

http://jsfiddle.net/jmpxgufu/185/

var ctx = document.getElementById(“ myChart”)。getContext(“ 2d”);

        var chart = {
        options: {
        scales: {
                 yAxes: [{ barPercentage: 1.0 }],
          },
      tooltips: {
         callbacks: {
            label: function(tooltipItem, data) {
console.log(tooltipItem);
           return data.datasets[tooltipItem.datasetIndex].label +': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].toLocaleString();
}
}
},          
          responsive: true,
          maintainAspectRatio: false,
          animation: {

                    onComplete: function(animation) {
                    }
                }
      },
        type: 'horizontalBar',
        data: {
            labels: ['Topic1'],
      datasets: [
      {
         label: 'Something',
         borderColor: 'blue',
         borderWidth: 1,
         backgroundColor: Color('blue').alpha(0.5).rgbString(),
         data: [40],
         fill: false
      },
      {
         label: 'Something else',
         borderColor: 'orange',
         borderWidth: 1,
         backgroundColor: Color('orange').alpha(0.5).rgbString(),
         data: [17],
         fill: false
      }
      ]
        }};

   var myLiveChart = new Chart(ctx, chart);

如果您查看图表,则有两个与标签“ Topic1”相关的条形图(橙色和蓝色)。

当我将鼠标悬停在橙色条上时,它说:

Topic1
Something: 40
Something else: 17

当我将鼠标悬停在蓝色栏上时,它说:

Topic1
Something: 40
Something else: 17

您还将注意到,由于该组中有两个小节,因此该函数执行了两次,将我返回的字符串作为输入,并形成此“分组”工具提示消息(我将console.log放入其中以表明它正在执行两次)。

我只想要悬停的栏的数据。

当我将鼠标悬停在橙色条上时,我要说:

Topic1
Something else: 17

当我将鼠标悬停在蓝色栏上时,我要说:

Topic1
Something: 40

但是,我还没有弄清楚如何确定哪个是活动的(两个)。

我在这里想念什么?

ɢʀᴜɴᴛ

要获得所需的行为,您需要将工具提示设置mode/nearest point

tooltips: {
   mode: 'nearest'
}

文档

#最近
获取最接近该点的项目。最接近的项目是根据距图表项目中心(点,条)的距离确定的。如果2个或2个以上的物品距离相同,则使用面积最小的物品。如果intersect为true,则仅在鼠标位置与图形中的项目相交时才触发。这对于组合图表非常有用,在组合图表中点隐藏在条形图后面。

这是工作中的小提琴

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章