Chart.JS中缺少数据的虚线(spanGaps样式) [英] Dashed line for missing data in Chart.JS (spanGaps style)
问题描述
我有一个图表,其中的数据点为空.Chart.js做正确的事,并跳过了这些数据点,但我想用虚线"填充缺少的部分.例如,在下面的代码中,该行应与CodePen链接中的相同,但应从蓝色"划线为黄色".我知道 spanGaps
选项可用,但我想对其应用其他样式.
I have a chart with data points that are null. Chart.js does the correct thing and skips those data points but I would like to have a 'dashed' line fill in the missing parts. For example, in the below code the line should be solid as in the CodePen link, but should be dashed from "Blue" to "Yellow". I know the spanGaps
option is available but I would like to apply a different style to it.
有人对如何实现这一目标有任何想法吗?我正在使用Chart.js 2.x
Does anyone have any thoughts on how to accomplish this? I am using Chart.js 2.x
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Red", "Blue", "Orange", "Yellow"],
datasets: [{
label: '# of Votes',
data: [12, 19, null, 3]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
推荐答案
插件核心API 提供了一系列可用于执行自定义代码的挂钩.您可以使用 beforeDraw
钩子直接在画布上使用
The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the beforeDraw
hook to draw lines of different style between different datapoints using text directly on the canvas using CanvasRenderingContext2D
.
请查看下面的可运行代码段:
Please take a look at the runnable code snippet below:
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
plugins: [{
beforeDraw: chart => {
var ctx = chart.chart.ctx;
ctx.save();
let xAxis = chart.scales['x-axis-0'];
let yAxis = chart.scales['y-axis-0'];
let dataset = chart.data.datasets[0];
var valueFrom = null;
var valueFromIndex = 0;
var xFrom = null;
let yFrom = null;
ctx.strokeStyle = dataset.borderColor;
dataset.data.forEach((value, index) => {
if (value != null) {
var x = xAxis.getPixelForTick(index);
var y = yAxis.getPixelForValue(value);
if (valueFrom != null) {
ctx.lineWidth = dataset.borderWidth;
if (index - valueFromIndex > 1) {
ctx.setLineDash([5, 5]);
} else {
ctx.setLineDash([]);
}
ctx.beginPath();
ctx.moveTo(xFrom, yFrom);
ctx.lineTo(x, y);
ctx.stroke();
}
valueFrom = value;
valueFromIndex = index;
xFrom = x;
yFrom = y;
}
});
ctx.restore();
}
}],
data: {
labels: ["A", "B", "C", "D", "E", "F", "G"],
datasets: [{
label: 'My Dataset',
data: [12, 19, null, 3, 6, null, 8],
backgroundColor: 'rgba(255, 99, 132, 0.6)',
borderColor: 'rgb(255, 99, 132)',
borderWidth: 3,
showLine: false,
}]
},
options: {
animation: {
duration: 0
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>
这篇关于Chart.JS中缺少数据的虚线(spanGaps样式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!