Good evening , I want to draw a horizontal line on a graph Bar Chart using Chart.js .
I read the question Chart.js – draw horizontal line and I could not draw the line on a Bar Chart, as indicated is the implementation for Line Chart.
My code is implemented to jsfiddle
HTML
JavaScript
x
4
1
<div>
2
<canvas id="ctx"></canvas>
3
</div>
4
JS
JavaScript
1
18
18
1
var data = {
2
labels: ["Docente 1", "Docente 2", "Docente 3", "Docente 4", "Docente 5", "Docente 6", "Docente 7"],
3
datasets: [
4
{
5
label: "Semestre 2017-I",
6
borderWidth: 1,
7
data: [3.65, 2.59, 1.80, 2.81, 0.56, 0.55, 3.40]
8
}
9
]
10
};
11
12
var ctx = document.getElementById("ctx");
13
14
var myBarChart = new Chart(ctx, {
15
type: 'bar',
16
data: data
17
});
18
and it would be able to draw the horizontal line, obtaining a graph of the form: http://i.stack.imgur.com/QlOKG.png
Advertisement
Answer
HTML:
JavaScript
1
4
1
<div>
2
<canvas id="ctx" width="600" height="400"></canvas>
3
</div>
4
JS:
JavaScript
1
37
37
1
var data = {
2
labels: ["Docente 1", "Docente 2", "Docente 3", "Docente 4", "Docente 5", "Docente 6", "Docente 7"],
3
datasets: [
4
{
5
label: "Semestre 2017-I",
6
borderWidth: 1,
7
data: [3.65, 2.59, 1.80, 2.81, 0.56, 0.55, 3.40]
8
}
9
]
10
};
11
12
var ctx = document.getElementById("ctx").getContext("2d");
13
14
Chart.types.Bar.extend({
15
name: "BarWithLine",
16
initialize: function () {
17
Chart.types.Bar.prototype.initialize.apply(this, arguments);
18
},
19
draw: function () {
20
Chart.types.Bar.prototype.draw.apply(this, arguments);
21
22
var lineHeight = 2; // <----
23
24
// draw line
25
this.chart.ctx.beginPath();
26
this.chart.ctx.moveTo(0, this.scale.calculateY(lineHeight));
27
this.chart.ctx.strokeStyle = '#ff0000';
28
this.chart.ctx.lineTo(this.chart.width, this.scale.calculateY(lineHeight));
29
this.chart.ctx.stroke();
30
}
31
});
32
33
var myBarChart = new Chart(ctx).BarWithLine(data, {
34
type: 'bar',
35
data: data
36
});
37
Here is the fiddle: http://jsfiddle.net/zk9oc4c9/
Important: I changed the Chart.js library URL to: http://www.chartjs.org/assets/Chart.min.js
And removed https from the fiddle.