Javascript Chart.js-在条形图中绘制水平线(条形类型)
晚上好,我想使用Chart.js在图形条形图上画一条水平线 我读了这个问题,但我无法在条形图上画出线,正如图中所示,这是折线图的实现 我的代码实现为 HTML 它将能够画出水平线,得到一个图形的形式: HTML:Javascript Chart.js-在条形图中绘制水平线(条形类型),javascript,jquery,chart.js,Javascript,Jquery,Chart.js,晚上好,我想使用Chart.js在图形条形图上画一条水平线 我读了这个问题,但我无法在条形图上画出线,正如图中所示,这是折线图的实现 我的代码实现为 HTML 它将能够画出水平线,得到一个图形的形式: HTML: <div> <canvas id="ctx" width="600" height="400"></canvas> </div> var data = { labels: ["Docente 1",
<div>
<canvas id="ctx" width="600" height="400"></canvas>
</div>
var data = {
labels: ["Docente 1", "Docente 2", "Docente 3", "Docente 4", "Docente 5", "Docente 6", "Docente 7"],
datasets: [
{
label: "Semestre 2017-I",
borderWidth: 1,
data: [3.65, 2.59, 1.80, 2.81, 0.56, 0.55, 3.40]
}
]
};
var ctx = document.getElementById("ctx").getContext("2d");
Chart.types.Bar.extend({
name: "BarWithLine",
initialize: function () {
Chart.types.Bar.prototype.initialize.apply(this, arguments);
},
draw: function () {
Chart.types.Bar.prototype.draw.apply(this, arguments);
var lineHeight = 2; // <----
// draw line
this.chart.ctx.beginPath();
this.chart.ctx.moveTo(0, this.scale.calculateY(lineHeight));
this.chart.ctx.strokeStyle = '#ff0000';
this.chart.ctx.lineTo(this.chart.width, this.scale.calculateY(lineHeight));
this.chart.ctx.stroke();
}
});
var myBarChart = new Chart(ctx).BarWithLine(data, {
type: 'bar',
data: data
});
JS:
<div>
<canvas id="ctx" width="600" height="400"></canvas>
</div>
var data = {
labels: ["Docente 1", "Docente 2", "Docente 3", "Docente 4", "Docente 5", "Docente 6", "Docente 7"],
datasets: [
{
label: "Semestre 2017-I",
borderWidth: 1,
data: [3.65, 2.59, 1.80, 2.81, 0.56, 0.55, 3.40]
}
]
};
var ctx = document.getElementById("ctx").getContext("2d");
Chart.types.Bar.extend({
name: "BarWithLine",
initialize: function () {
Chart.types.Bar.prototype.initialize.apply(this, arguments);
},
draw: function () {
Chart.types.Bar.prototype.draw.apply(this, arguments);
var lineHeight = 2; // <----
// draw line
this.chart.ctx.beginPath();
this.chart.ctx.moveTo(0, this.scale.calculateY(lineHeight));
this.chart.ctx.strokeStyle = '#ff0000';
this.chart.ctx.lineTo(this.chart.width, this.scale.calculateY(lineHeight));
this.chart.ctx.stroke();
}
});
var myBarChart = new Chart(ctx).BarWithLine(data, {
type: 'bar',
data: data
});
var数据={
标签:[“文件1”、“文件2”、“文件3”、“文件4”、“文件5”、“文件6”、“文件7”],
数据集:[
{
标签:“Semestre 2017-I”,
边框宽度:1,
数据:[3.65,2.59,1.80,2.81,0.56,0.55,3.40]
}
]
};
var ctx=document.getElementById(“ctx”).getContext(“2d”);
Chart.types.Bar.extend({
名称:“BarWithLine”,
初始化:函数(){
Chart.types.Bar.prototype.initialize.apply(这是参数);
},
绘图:函数(){
Chart.types.Bar.prototype.draw.apply(这是参数);
var lineHeight=2;//这可能会有帮助&&我的情况与上面不同,我希望这条线是水平的。答案是肯定的,我认为这会对您有所帮助。无论如何,您接受的答案与我上面发布的JSFIDLE链接的代码类似。水平线和曲线之间的差异取决于您传递的数据。