gpt4 book ai didi

javascript - Chart.js - 在条形图中绘制水平线(类型 bar)

转载 作者:行者123 更新时间:2023-11-30 11:54:10 24 4
gpt4 key购买 nike

晚上好,我想使用 Chart.js 在图表条形图上绘制一条水平线。

我阅读了问题 Chart.js - draw horizontal line而且我无法在条形图上画线,如折线图的实现所示。

我的代码实现到jsfiddle

HTML

<div>
<canvas id="ctx"></canvas>
</div>

JS

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");

var myBarChart = new Chart(ctx, {
type: 'bar',
data: data
});

它可以绘制水平线,得到如下形式的图形: http://i.stack.imgur.com/QlOKG.png

最佳答案

HTML:

<div>
<canvas id="ctx" width="600" height="400"></canvas>
</div>

JS:

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
});

这是 fiddle :http://jsfiddle.net/zk9oc4c9/

重要提示:我将 Chart.js 库 URL 更改为: http://www.chartjs.org/assets/Chart.min.js

并从 fiddle 中删除了 https。

关于javascript - Chart.js - 在条形图中绘制水平线(类型 bar),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38561420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com