meridbt
meridbt

Reputation: 397

How to get the X position at a specified chart item index?

I'm drawing a Bar chart with multiple datasets and need to draw a vertical line at a specified item index, i.e.

// chartData:
{
  labels: ['lbl0', 'lbl1', 'lbl2'],
  datasets: [{
    label: 'dataset1',
    data: [12.84, 13.75, 14.86]
  },
  {
    label: 'dataset2,
    data: [25.14, 15.61, 10.81]
  }]
}

is there any way to get the X coordinate of first or all tooltips belonging to label lbl1?

Upvotes: 0

Views: 143

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31371

Yes you can use getPixelForValue

const chart = new Chart(ctx, config);
const x = chart.scales.x.getPixelForValue('lbl1');

You can also choose to use the annotation plugin where you can just give the label and it will draw the line for you:

https://www.chartjs.org/chartjs-plugin-annotation/

Upvotes: 1

Related Questions