如何根据 chart.js 中的标签值更改线段颜色?
How to change line segment color based on label value in chart.js?
有一个example如何根据点值改变线段颜色,有这样的功能
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>
有一个example如何根据点值改变线段颜色,有这样的功能
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>