score:95
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
<div>
<canvas id="linewithline" width="600" height="400"></canvas>
</div>
script
var data = {
labels: ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"],
datasets: [{
data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1]
}]
};
var ctx = document.getelementbyid("linewithline").getcontext("2d");
chart.types.line.extend({
name: "linewithline",
draw: function () {
chart.types.line.prototype.draw.apply(this, arguments);
var point = this.datasets[0].points[this.options.lineatindex]
var scale = this.scale
// draw line
this.chart.ctx.beginpath();
this.chart.ctx.moveto(point.x, scale.startpoint + 24);
this.chart.ctx.strokestyle = '#ff0000';
this.chart.ctx.lineto(point.x, scale.endpoint);
this.chart.ctx.stroke();
// write today
this.chart.ctx.textalign = 'center';
this.chart.ctx.filltext("today", point.x, scale.startpoint + 12);
}
});
new chart(ctx).linewithline(data, {
datasetfill : false,
lineatindex: 2
});
the option property lineatindex controls which point to draw the line at.
fiddle - http://jsfiddle.net/dbyze2ga/14/
score:4
here's a pen that achieves a similar effect without the chartjs-plugin-annotation, or hacking how chart.js renders, or any other plugins: https://codepen.io/gkemmey/pen/qbwzbym
approach
- use a combo bar / line chart, and use the bar chart to draw the vertical lines.
- use two y-axes: one for the bar chart (which we don't display), and one for all your other line chart datasets.
- force the bar chart y-axes to
min: 0
andmax: 1
. anytime you want to draw a vertical line, add a data object like{ x: where_the_line_goes, y: 1 }
to your bar chart dataset. - the pen also adds some custom data to the bar chart dataset and a legend filter and label callback to exclude the bar chart dataset from the legend, and control the label on the vertical line.
pros
- no other dependencies. no custom monkey patching / extending.
- the annotations plugin doesn't seem to be actively maintained. for instance, atm, their event handlers throw an error about "preventing default on passive events"
- maybe a pro: the annotations plugin always shows the labels of lines drawn, and you have to use their event callbacks to get a show-on-hover effect. chart.js tooltips show on hover by default.
cons
- we're adding custom data in the dataset config, and hoping it doesn't conflict with anything chart.js is doing. it's data chart.js doesn't expect to be there, but as of 2.8, also doesn't break it.
score:7
i had to go through the trouble of figuring out how to do something similar with chartjs 2.0 so i thought i would share.
this is based on the new way of overriding a chart prototype as explained here: https://github.com/chartjs/chart.js/issues/2321
var ctx = document.getelementbyid('income-chart');
var originaldraw = chart.controllers.line.prototype.draw;
chart.controllers.line.prototype.draw = function (ease) {
originaldraw.call(this, ease);
var point = datavalues[vm.incomecentile];
var scale = this.chart.scales['x-axis-0'];
// calculate the portion of the axis and multiply by total axis width
var left = (point.x / scale.end * (scale.right - scale.left));
// draw line
this.chart.chart.ctx.beginpath();
this.chart.chart.ctx.strokestyle = '#ff0000';
this.chart.chart.ctx.moveto(scale.left + left, 0);
this.chart.chart.ctx.lineto(scale.left + left, 1000000);
this.chart.chart.ctx.stroke();
// write label
this.chart.chart.ctx.textalign = 'center';
this.chart.chart.ctx.filltext('you', scale.left + left, 200);
};
score:8
i'd highly recommend to use the chartjs-plugin-annotation.
an example can be found at codepen
var chartdata = {
labels: ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"],
datasets: [
{
data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1]
}
]
};
window.onload = function() {
var ctx = document.getelementbyid("canvas").getcontext("2d");
new chart(ctx, {
type: "line",
data: chartdata,
options: {
annotation: {
annotations: [
{
type: "line",
mode: "vertical",
scaleid: "x-axis-0",
value: "mar",
bordercolor: "red",
label: {
content: "today",
enabled: true,
position: "top"
}
}
]
}
}
});
};
have a look here for more details: https://stackoverflow.com/a/36431041
score:71
sharing my solution for chartjs.org version 2.5. i wanted to use a plugin, to make the implementation reusable.
const verticallineplugin = {
getlineposition: function (chart, pointindex) {
const meta = chart.getdatasetmeta(0); // first dataset is used to discover x coordinate of a point
const data = meta.data;
return data[pointindex]._model.x;
},
renderverticalline: function (chartinstance, pointindex) {
const lineleftoffset = this.getlineposition(chartinstance, pointindex);
const scale = chartinstance.scales['y-axis-0'];
const context = chartinstance.chart.ctx;
// render vertical line
context.beginpath();
context.strokestyle = '#ff0000';
context.moveto(lineleftoffset, scale.top);
context.lineto(lineleftoffset, scale.bottom);
context.stroke();
// write label
context.fillstyle = "#ff0000";
context.textalign = 'center';
context.filltext('my text', lineleftoffset, (scale.bottom - scale.top) / 2 + scale.top);
},
afterdatasetsdraw: function (chart, easing) {
if (chart.config.lineatindex) {
chart.config.lineatindex.foreach(pointindex => this.renderverticalline(chart, pointindex));
}
}
};
chart.plugins.register(verticallineplugin);
usage is simple then:
new chart(ctx, {
type: 'line',
data: data,
label: 'progress',
options: options,
lineatindex: [2,4,8],
})
the code above inserts red vertical lines at positions 2,4 and 8, running through points of first dataset at those positions.
Source: stackoverflow.com
Related Query
- Chart.js — drawing an arbitrary vertical line
- Remove the vertical line in the chart js line chart
- Moving vertical line when hovering over the chart using chart.js
- How do I draw a vertical line on a horizontal bar chart with ChartJS?
- Draw a horizontal and vertical line on mouse hover in chart js
- ChartJS: Draw vertical line at data point on chart on mouseover
- chartjs - Drawing vertical line on integer x axis value
- Drawing line chart in chart.js with json response
- Drawing line chart in chart.js placing dots only when value changes
- Chart js vertical line z-index
- In Stacked horizontal bar chart how to remove the vertical line in Chart.js?
- Chartjs: Need help on drawing a vertical line when hovering cursor
- display vertical axis label in line chart using chart.js
- Drawing line chart in chart.js with json data
- Change horizontal line chart to vertical line
- vertical grid line not taking full hight of the canvas in chart js 3.3.2
- With Chart js, I am trying to color every 7th vertical (x axis) grid line (representing each week beginning visually)
- Vertical Line chart with ChartJS
- drawing line chart with chartjs
- Animation chart js (line), animate chart drawing line by line
- ReactJS - Moving vertical line when hovering over Line chart using chart.js v3.7.1
- Moving vertical line when hovering over the chart using chart.js in v2.9.4
- Drawing a horizontal line on a stacked bar chart on hover (chart js)
- Line chart is drawing before first point in Chart.js
- How to add vertical line in bar chart using chartJs and ng2-charts?
- Change Vertical Line and Color bar chart in bar chart.js
- How to create vertical arbitrary line in financial chart?
- Limit labels number on Chart.js line chart
- Chart.js - How to set a line chart dataset as disabled on load
- Chart Js Change Label orientation on x-Axis for Line Charts
More Query from same tag
- Aligning zero on y axis to the labels on x axis of line chart in chartjs
- Add value to horizontal bar in chart.js
- Chart.js - disable tooltip when cursor moves outside the main canvas
- Charts JS: Doughnut chart and hiding tooltip for specific data index within each dataset
- Parsing error: Unexpected token, expected ";" line 54 in .map function
- How to clear the data for a angular-chart
- How to create a scatter plot where x-axis represents a day by hours with datetime object? chartJS
- Chartisan/Laravel - > "Call to undefined method" error
- Chart.js - (intermediate value).Doughnut is not a function
- Auto center ticks and values on graph when there's only one with chart.js
- How to integrate basic ChartJs customizations when using react-chartjs-2?
- Vue Chart.js Doughnut Chart with rounded and spaced arcs (vue3-chart-v2)
- In a bar graph can the lower numbers be made to have the taller bars?
- How to hide the tick marks of the axis in react-chartjs-2
- Chart.js - IndexSizeError: Index or size is negative or greater than the allowed amount
- Assigning data structures to chartjs properties, NOT individually
- Generate Chart With 2 Datasets Charts.js
- Bar Chart not displaying when using chart.js
- Display two datasets from an array using chart.js in node.js
- Chart js show/hide legend during runtime via buttonClick
- Chartjs fiddle not working
- How to group chart labels together?
- How to change number to $ with commas? Chart.js
- Vuejs - Chart.js wrapper vue3-chart-v2 not displaying labels when data are passed as object
- ChartJS - x axis labels orientation
- Drawing a doughnut chart with columns inside to represent hourly stats in chart.js
- hiding x-axes labels with 0 values on a bar chart
- Chart.js stacked bar chart text on top of the stacked bars
- How to send data from struts2 to a javascript function to draw a chart
- How to draw the stroke behind bars in Chart.js?