vertical line at specific x-ax value

215 views
Skip to first unread message

Angelo van Cleef

unread,
Nov 3, 2022, 9:51:47 AM11/3/22
to Chart.js User Discussion
Hey guys, have been searching for hours but I cannot find a (working) solution. Can anyone tell me how I can add a vertical line at a specific x-axis (date i.e. 2022-10-01) value?

I am using Nuxt and ChartJS. I am able to add a custom plugin but am clueless on how to iterate over the x-axis.

Peak

unread,
Nov 3, 2022, 1:01:31 PM11/3/22
to Chart.js User Discussion
Do you have some code to publish on jsFiddle or similar?

Nicky Wong

unread,
Nov 3, 2022, 1:44:28 PM11/3/22
to Peak, Chart.js User Discussion
Hi Angelo,

Not sure if Nuxt is very different from basic JS. Have you seen this video: https://youtu.be/zAOls0NC8xI
It creates a line based on todays date. 

--
You received this message because you are subscribed to the Google Groups "Chart.js User Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to chartjs-user-disc...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/chartjs-user-discussion/95a9d547-bc81-46c6-ad4a-0ce8ea9d7c51n%40googlegroups.com.

Angelo van Cleef

unread,
Nov 4, 2022, 5:11:16 AM11/4/22
to Chart.js User Discussion
I am using a plugin at the moment.

const VerticalLinePlugin = {
     afterDraw (chart, args, options) {
          const ctx = chart.ctx
          ctx.save()

          const yAxis = chart.scales['y-axis-0']
          const xAxis = chart.scales['x-axis-0']

          const x = xAxis.getPixelForValue('2022-10-26')
          ctx.beginPath()
          ctx.moveTo(yAxis.top, x)
          ctx.lineTo(yAxis.bottom, x)     
          ctx.lineWidth = 2
          ctx.strokeStyle = "green"
          ctx.stroke()
          ctx.restore()
     }
}

In my x-axis I have dates, what I would like to do is have a vertical line from bottom to top across the graph where the date "2022-10-26" is displayed.

Above code does draw a line, but it is a horizontal line and not a vertical line. It also is not exactly on point on the date.

Op donderdag 3 november 2022 om 18:44:28 UTC+1 schreef Nick:

Angelo van Cleef

unread,
Nov 4, 2022, 5:18:40 AM11/4/22
to Chart.js User Discussion
I got it working. Below is the working code. Thanks for your help and suggestions everyone!



afterDraw (chart, args, options) {
const ctx = chart.ctx
ctx.save()

const yAxis = chart.scales['y-axis-0']
const xAxis = chart.scales['x-axis-0']

const x = xAxis.getPixelForValue('2022-10-26')

ctx.beginPath()
ctx.moveTo(x, yAxis.top)
ctx.lineTo(x, yAxis.bottom)

ctx.lineWidth = 2
ctx.strokeStyle = "green"
ctx.stroke()

ctx.restore()
}
}

Op vrijdag 4 november 2022 om 10:11:16 UTC+1 schreef Angelo van Cleef:
Reply all
Reply to author
Forward
0 new messages