I would like to draw a horizontal line in a chart using Chart.js. But I\'m not able to do it.
I\'ve read this question - Chart.js — drawing an arbitrary vertical lin
Based on dFelinger message I made a new char type that draws an average line on the line chart. Here's the code, just copy and call a new chart with the new type called 'lineWithAverage' WORKS ONLY FOR CHARTJS 2
Chart.controllers.lineWithAverage = Chart.controllers.line.extend({
initialize: function () {
Chart.controllers.line.prototype.initialize.apply(this, arguments);
},
draw: function () {
Chart.controllers.line.prototype.draw.apply(this, arguments);
var scale = this.scale
var sum = 0;
this.getDataset().data.forEach(function(value) {
sum = sum + value;
});
var average = sum / this.getDataset().data.length;
var averageCoord = this.calculatePointY(average);
// draw line
this.chart.chart.canvas.ctx = this.chart.chart.canvas.getContext('2d');
this.chart.chart.canvas.ctx.beginPath();
this.chart.chart.canvas.ctx.moveTo(0, averageCoord);
this.chart.chart.canvas.ctx.strokeStyle = '#979797';
this.chart.chart.canvas.ctx.lineTo(this.chart.chart.width, averageCoord);
this.chart.chart.canvas.ctx.stroke();
}
});