angularchart.jsbar-chartlinechartcombo-chart

How to draw horizontal line in chart js which when hovered shows the data


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',
      }
    }
  },
})
}

I want that the total recordings line graph should be a horizontal straight line and whenever I hover over the line it should show total recordings value. Right now graph is getting plot as shown in image. current chart img


Solution

  • I finally found the way out. The answer to this is a floating bar

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

    Further to correctly show the total recordings data when you hover, use this

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