How can I draw an vertical line at a particular point on the x-axis using Chart.js?
In particular, I want to draw a line to indicate the current day on a LineChart. Here’s a mockup of the chart: http://i.stack.imgur.com/VQDWR.png
Advertisement
Answer
Update – this answer is for Chart.js 1.x, if you are looking for a 2.x answer check the comments and other answers.
You extend the line chart and include logic for drawing the line in the draw function.
Preview
HTML
JavaScript
x
4
1
<div>
2
<canvas id="LineWithLine" width="600" height="400"></canvas>
3
</div>
4
Script
JavaScript
1
35
35
1
var data = {
2
labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
3
datasets: [{
4
data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1]
5
}]
6
};
7
8
var ctx = document.getElementById("LineWithLine").getContext("2d");
9
10
Chart.types.Line.extend({
11
name: "LineWithLine",
12
draw: function () {
13
Chart.types.Line.prototype.draw.apply(this, arguments);
14
15
var point = this.datasets[0].points[this.options.lineAtIndex]
16
var scale = this.scale
17
18
// draw line
19
this.chart.ctx.beginPath();
20
this.chart.ctx.moveTo(point.x, scale.startPoint + 24);
21
this.chart.ctx.strokeStyle = '#ff0000';
22
this.chart.ctx.lineTo(point.x, scale.endPoint);
23
this.chart.ctx.stroke();
24
25
// write TODAY
26
this.chart.ctx.textAlign = 'center';
27
this.chart.ctx.fillText("TODAY", point.x, scale.startPoint + 12);
28
}
29
});
30
31
new Chart(ctx).LineWithLine(data, {
32
datasetFill : false,
33
lineAtIndex: 2
34
});
35
The option property lineAtIndex controls which point to draw the line at.
Fiddle – http://jsfiddle.net/dbyze2ga/14/