如何在chart.js中根据标签值改变线段颜色?



有一个如何根据点值改变线段颜色的例子,函数如下

borderColor: function(context) {
if (context.p0.parsed.y == 5){
return 'transparent';
}
},

我想根据标签的值设置颜色。这行不通:

context.p0.parsed.x == 'February'

在今天发布的新版本chart.js(3.6.0)中,您可以访问图表对象并获得dataIndex,以便您可以在标签数组中检查它,如下所示:

const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
segment: {
borderColor: (ctx) => (ctx.chart.data.labels[ctx.p0DataIndex] === "Green" ? "Pink" : "Orange")
}
}]
},
options: {}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.6.0/dist/chart.min.js"></script>
</body>

最新更新