我想用Chart.js在图表中画一条水平线。但是我做不到。
我找到了这个example,但我在将其转换为条形图时遇到了问题,因为它使用点来确定放置线条的位置,而条形图似乎没有使用“点”
var data = {
labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
datasets: [{
data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1]
}]
};
var ctx = document.getElementById("LineWithLine").getContext("2d");
Chart.types.Line.extend({
name: "LineWithLine",
initialize: function () {
Chart.types.Line.prototype.initialize.apply(this, arguments);
},
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
var point = this.datasets[0].points[this.options.lineAtIndex]
var scale = this.scale
console.log(this);
// draw line
this.chart.ctx.beginPath();
this.chart.ctx.moveTo(scale.startPoint+12, point.y);
this.chart.ctx.strokeStyle = '#ff0000';
this.chart.ctx.lineTo(this.chart.width, point.y);
this.chart.ctx.stroke();
// write TODAY
this.chart.ctx.textAlign = 'center';
this.chart.ctx.fillText("TODAY", scale.startPoint + 35, point.y+10);
}
});
new Chart(ctx).LineWithLine(data, {
datasetFill : false,
lineAtIndex: 2
});<script src="http://www.chartjs.org/assets/Chart.min.js"></script>
<div>
<canvas id="LineWithLine" width="600" height="400"></canvas>
</div>
在Chart.js 2中有没有更好的方法来做到这一点?也许是使用折线图和条形图的组合,或者这是不是有点夸张?
希望你们能帮助我解决这个问题,我已经使用CSS和Javascript创建了这个图表,如下所示:

在这个例子中,限制是一个负值,所以它将自己绘制在实际的线下,这可能会让人感到困惑,但主要的事情是,这条线是以我选择的值绘制的。:)
发布于 2017-06-02 23:41:05
如果您仍然有这个问题,请查看这个关于drawing a custom horizontal line in Chart.js 2的问题
在我链接的问题的答案中,它在chart.js中定义了一个新的插件(在Chart.js的网站上有更多信息),允许你绘制条形图和自定义线条。还有一个jsfiddle可以更好地理解插件的工作方式
https://stackoverflow.com/questions/42270458
复制相似问题