如何在chartjs2中绘制具有不同颜色的一条线?
问题描述:
我需要画一张看起来像图片上的图表.我该如何使用chartjs2?不幸的是,我找不到任何示例来展示如何实现它.
I need to draw a chart that looks like the one on the picture. How do I do that with chartjs2? Unfortunately, I couldn't find any examples that show how to implement it.
答
首先将您的line
图表转换为scatter
图表.然后使用插件核心在画布上直接绘制线条API .该API提供了一系列可用于执行自定义代码的挂钩.
First convert your line
chart into a scatter
chart. Then draw the lines directly on the canvas using the Plugin Core API. The API offers a range of hooks that may be used for performing custom code.
在下面的代码片段中,我使用beforeDraw
钩子在数据点之间绘制不同颜色的连接线.
In below code snippet, I use the beforeDraw
hook to draw connection lines of different colors between data points.
const values = [11,9,7,8,7,11,13,12,7,12];
const colors = ['red','red','orange','orange','green','green','orange','red','green'];
const data = values.map((value, index) => ( { x: index + 1, y: value, color: index == 0 ? undefined: colors[index - 1]} ));
const colorsPer100 = ['green', 'orange', 'blue', 'red'];
new Chart(document.getElementById("myChart"), {
type: "scatter",
plugins: [{
beforeDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-1'];
var yAxis = chart.scales['y-axis-1'];
chart.config.data.datasets[0].data.forEach((value, index) => {
if (index > 0) {
var valueFrom = data[index - 1];
var xFrom = xAxis.getPixelForValue(valueFrom.x);
var yFrom = yAxis.getPixelForValue(valueFrom.y);
var xTo = xAxis.getPixelForValue(value.x);
var yTo = yAxis.getPixelForValue(value.y);
ctx.save();
ctx.strokeStyle = value.color;
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(xFrom, yFrom);
ctx.lineTo(xTo, yTo);
ctx.stroke();
ctx.restore();
}
});
}
}],
data: {
datasets: [{
label: "My Dataset",
data: data,
borderColor: "black"
}]
},
options: {
animation: {
duration: 0
},
legend: {
display: false
},
scales: {
xAxes: [{
ticks: {
min: 0,
max: 12,
stepSize: 1
}
}],
yAxes: [{
ticks: {
min: 0,
max: 14,
stepSize: 2
}
}]
}
}
});
canvas {
max-width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" width="10" height="6"></canvas>