ChartJS 如何在图表js中绘制水平线,当悬停显示数据

wsewodh2  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(166)
ngOnInit(): void {

var myChart = new Chart('myChart', {
  type: 'bar',
  data: {
    labels: ['Recordings'],
    datasets: [
      {
        label: 'A',
        data: [this.data.a],
        borderColor: 'rgba(255,105,180,1)',
        backgroundColor: 'rgba(255,105,180,0.2)',
        barPercentage:0.4,
        borderWidth:2,
        order: 1
      },
      {
        label: 'B',
        data: [this.data.b],
        borderColor: 'rgba(75, 192, 192, 1)',
        backgroundColor: 'rgba(75, 192, 192, 0.2)',
        barPercentage:0.4,
        borderWidth:2,
        order: 2
      },
      {
        label: 'Total Recordings',
        data:[this.data.totalrecordings],
        type:'line',
        borderColor:'rgba(2,117,216,1)',
        backgroundColor:'rgba(2,117,216,0.2)',
        order:0
      }
    ]
  },
  options: {
    responsive: true,
    plugins: {
      legend: {
        position: 'top',
      }
    }
  },
})
}

我希望总记录折线图应该是一条水平直线,当我将鼠标悬停在该直线上时,它应该显示总记录值。现在,该图正在绘制,如图所示。

2w2cym1i

2w2cym1i1#

我终于找到了出路。答案是一个漂浮的酒吧

{
  label: 'Total Recordings',
  data: [[data.totalrecordings -0.5, data.totalrecordings + 0.5]]
  categoryPercentage: 1,
  barPercentage: 1,
  borderColor:'rgba(2,117,216,1)',
  backgroundColor:'rgba(2,117,216,0.2)',
  order:0
}

此外,要在悬停时正确显示总记录数据,请使用此

tooltip: {
   mode: 'index',
   callbacks: {
        label: ctx => ctx.dataset.label + ': ' + (ctx.datasetIndex == 2 ? 
                     data.totalrecordings : ctx.parsed.y)
   }
}

相关问题