In the below example, the chartjs annotation works with a string value ("MAR"
), but not with an integer value. How do I draw a vertical line on some integer x-axis value.
var chartData = {
labels: ["JAN", "FEB", "MAR"],
datasets: [
{
data: [12, 3, 2]
}
]
};
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: 2,
borderColor: "red",
label: {
content: "TODAY",
enabled: true,
position: "top"
}
}
]
}
}
});
};
See fiddle: https://codepen.io/anon/pen/QaQWba
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 and max: 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.
You can set the pointRadius to zero. I've added "borderWidth: 1" and "pointRadius: 0.5" because I also needed a fine line and tiny dots to hover over them. I needed to add pointHitRadius: 0 as well to disable tooltips.
You can achieve your goal passing data as points, configuring xAxes
as linear and creating a custom tick format:
Data:
var chartData = {
labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
datasets: [
{
data: [{x: 1, y: 12}, {x: 2, y: 3}, {x: 3, y: 2}, {x: 4, y: 1}, {x: 5, y: 8}, {x: 6, y: 8}, {x: 7, y: 2}, {x: 8, y: 2}, {x: 9, y: 3}, {x: 10, y: 5}, {x: 11, y: 11}, {x: 12, y: 1}];
}
]
};
xAxes config:
xAxes: [{
type: 'linear',
position: 'bottom',
ticks: {
max: 12,
min: 1,
stepSize: 1,
callback: function(value, index, values) {
return chartData.labels[index];
}
}
}]
Check the CodePen updated: https://codepen.io/beaver71/pen/XVZXOM
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With