我想绘制X轴,即Y = 0处的水平线,以更好地看到Y的正负值在哪里。
我想要这样的事情:
这可以在Chart.js
中使用编辑1
我想在Chart对象中绘制线条,以便能够与它进行交互。例如:X轴上的点可以绘制为绿色,下面的点可以是红色。
答案 0 :(得分:1)
您可以使用:
scales: {
xAxes: [{
gridLines: {
zeroLineWidth: 3,
zeroLineColor: "#2C292E",
},
}]
}
Blockquote
答案 1 :(得分:0)
您可以扩展图表以执行两项操作 - 绘制线条并为点着色
Chart.types.Line.extend({
name: "LineAlt",
initialize: function (data) {
Chart.types.Line.prototype.initialize.apply(this, arguments);
this.datasets.forEach(function (dataset, i) {
dataset.points.forEach(function (point) {
// color points depending on value
if (point.value < 0) {
// we set the colors from the data argument
point.fillColor = data.datasets[i].pointColor[0];
} else {
point.fillColor = data.datasets[i].pointColor[1];
}
// we need this so that the points internal color is also updated - otherwise our set colors will disappear after a tooltip hover
point.save();
})
})
},
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
// draw y = 0 line
var ctx = this.chart.ctx;
var scale = this.scale;
ctx.save();
ctx.strokeStyle = '#ff0000';
ctx.beginPath();
ctx.moveTo(Math.round(scale.xScalePaddingLeft), scale.calculateY(0));
ctx.lineTo(scale.width, scale.calculateY(0));
ctx.stroke();
ctx.restore();
}
});
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
// point color is a an array instead of a string
pointColor: ["rgba(220,0,0,1)", "rgba(0,220,0,1)"],
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, -56, -55, 40]
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
// use our new chart type LineAlt
var myNewChart = new Chart(ctx).LineAlt(data);