我正在尝试使用Chart.js在折线图中添加空数据点。我有这个:
var data = {
labels: [
"1","2","3","4","5","6","7","8","9","10"
],
datasets: [
{
label: "Traffic",
data: null,null,20,40,null,null,null,10,20,null
}
]
};
问题是线图仅将前两个“空值”识别为空数据点,并且不显示它们。但是,对于之后的空值,会显示一行(连接上一个和下一个有效数据点),这使得它看起来好像“null”-datapoints实际存在。有没有办法在线图中不显示空值? (类似于Canvas.js提供的:http://canvasjs.com/docs/charts/basics-of-creating-html5-chart/empty-null-data-points-chart/)
我通读了Chart.js文档和stackoverflow但找不到答案。谁能帮我?
在Line ChartJS empty / null values doesn't break the line上发布答案摘要,对上述问题进行(轻微)更正
扩展折线图
Chart.types.Line.extend({
name: "LineAlt",
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
// now draw the segments
var ctx = this.chart.ctx
this.datasets.forEach(function (dataset) {
ctx.strokeStyle = dataset.strokeColor
var previousPoint = {
value: null
};
dataset.points.forEach(function (point) {
if (previousPoint.value !== null && point.value !== null) {
ctx.beginPath();
ctx.moveTo(previousPoint.x, previousPoint.y);
ctx.lineTo(point.x, point.y);
ctx.stroke();
}
previousPoint = point;
})
})
}
});
你必须这样调用LineAlt
var myLineChart = new Chart(ctx).LineAlt(data, {
datasetStrokeWidth: 0.01,
datasetFill: false,
pointDotRadius : 2,
pointDotStrokeWidth: 3
});
对您的问题进行的其他更改 - 数据应该是数组而不是逗号分隔的值集值
小提琴 - http://jsfiddle.net/zu3p2nky/
现在这可以在不需要扩展的情况下开箱即用,只需使用null
作为数据点即可。
我读了line documentation并找到了一个名为spanGaps
的布尔选项
这是一段代码,我用它来显示:
{
'type': 'line',
'data': {
'labels': [1, 2, 3, 4, 5],
'datasets': [{
'label': 'example',
'data': [4, 1, null, 3],
// These are style properties, there is no need to copy them
'borderColor': 'rgba(255,99,132,1)',
'borderWidth': 1,
'fill': false,
tension: 0.2,
}]
},
'options': {
spanGaps: true // this is the property I found
}
}
与spanGaps = false
的图表: