I'm struggling drawing a line on a bar chart as shown here
https://stackoverflow.com/questions/39293816/how-to-draw-horizontal-line-on-bar-chart-chartjs
Maybe there is a simple way to do that ?
I would also want to draw multiple lines on different values on Y axis..
Well, the solution is in the stackoverflow post...
You have to make plugin and use LineTo.
You can add inline plugins in vue-chartjs with addPlugin()
http://vue-chartjs.org/#/home?id=inline-plugins
Please use stackoverflow for this kind of questions, as it's not really realated to vue-chartjs ;)
hi @apertureless,
I did as you suggested:
export default {
extends: Bar,
props: ['data', 'options'],
mounted () {
var horizonalLinePlugin = {
id: 'horizontalLine',
afterDraw: function(chartInstance) {
var yValue;
var yScale = chartInstance.scales["y-axis-0"];
var canvas = chartInstance.chart;
var ctx = canvas.ctx;
var index;
var line;
var style;
if (chartInstance.options.horizontalLine) {
for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
line = chartInstance.options.horizontalLine[index];
if (!line.style) {
style = "#080808";
} else {
style = line.style;
}
if (line.y) {
yValue = yScale.getPixelForValue(line.y);
} else {
yValue = 0;
}
ctx.lineWidth = 3;
if (yValue) {
window.chart = chartInstance;
ctx.beginPath();
ctx.moveTo(0, yValue);
ctx.lineTo(canvas.width, yValue);
ctx.strokeStyle = style;
ctx.stroke();
}
if (line.text) {
ctx.fillStyle = style;
ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
}
}
return;
}
}
};
this.addPlugin(horizonalLinePlugin);
this.renderChart(this.data, this.options)
}
and creating multiple charts in this way
@foreach($charts as $chart)
<div style="margin-top:30px">
<targets-chart
:data="{
labels: [...],
datasets: [
{
label: '...',
backgroundColor: '#f87979',
data: [...],
}
],
}"
:options="{
tooltips: {
callbacks: {
title: function(tooltipItems, data) {
return '...'
},
label: function(tooltipItems, data) {
....
}
}
},
horizontalLine: [{ y: 12000000}]
}"
:width="200"
:height="50"
></targets-chart>
</div>
@endforeach
I see the the code reaches the part inside the mount() function and it runs the code inside the plugin. But still can't see anything.
When I do window.chart = chartInstance
and then trying to create line after page loaded..it works only then.
Any idea if I'm doing something wrong here ?
Can you maybe provide a minimal codepen for reproduction?
closed due to inactivity
Hi, there.
I create this pen for implement horizontal line, as example
@guibragamonte
Hi, in your code there is one problem: the tooltip appeared behind line (you can see it if mouse over the red bar).
I solved this issue (in my case) by changing afterDraw method to afterDatasetDraw
Most helpful comment
@guibragamonte
Hi, in your code there is one problem: the tooltip appeared behind line (you can see it if mouse over the red bar).
I solved this issue (in my case) by changing afterDraw method to afterDatasetDraw