我想使用Chart.js在图表中绘制一条水平线。但我做不到。
我找到了这个例子,但是我在将它转换为条形图时遇到了麻烦,因为它使用点来确定放置折线的位置,而条形图似乎没有使用“点”
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 创建了这个图表,如下所示:
在这个例子中,限制是一个负值,所以它在实际线下方绘制了自己的图表,这可能会令人困惑,但主要的是这条线是在我选择的值处绘制的。:)