我指的是有关Stack Overflow的帖子:
这篇文章中提到的代码基于图形上一个点的位置创建一条水平线。假设我在42点处有一个点,在44点处有一个点,那么我可以选择在其中一个点上划一条线。
但是在我当前的场景中,我想要一个点(例如)在43,这将很难绘制,因为该点没有“最高值”(其他两个在Chart.js中计算出最高值)。例如,在Chart.js中是否可以通过计算该行所需的“最高值”来做到这一点?在我的实际图形中,我没有像42和44这样的点可以对它们进行平均并找到43,我需要像39和55这样的点,我需要在43处画一条线。
只需利用scale.calculateY
做
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("myChart").getContext("2d");
Chart.types.Line.extend({
name: "LineWithYLine",
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
var scale = this.scale
var ctx = this.chart.ctx;
// calculate using the scale
var y = scale.calculateY(this.options.lineAtValue);
// draw line
ctx.save();
ctx.strokeStyle = '#ff0000';
ctx.beginPath();
ctx.moveTo(Math.round(scale.xScalePaddingLeft), y);
ctx.lineTo(this.chart.width, y);
ctx.stroke();
ctx.restore();
}
});
new Chart(ctx).LineWithYLine(data, {
datasetFill: false,
lineAtValue: 7.5
});
如果要绘制标签,可以调整行的末端位置以留出空间。然后使用相同的y值在那里绘制文本。
如果您的图表数据点不能使比例尺足够拉伸(例如,比例尺从0到10,但是您想在12处画一条线),请使用chart.js选项覆盖比例尺。
小提琴-http: //jsfiddle.net/gywzg9e4/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句