将线色颜色更改低于图表中的特定值。
我正在尝试为特定值以下的一定颜色上下颜色。我正在使用Chart.js v3.7.1
href =“ https://stackoverflow.com/a/69691397/1725871”中找到的解决方案
我已经实现了在< a href =“ https://i.sstatic.net/rka48.png” rel =“ nofollow noreferrer”>
let posColour= 'rgb(86,188,77)';
let negColour= 'rgb(229,66,66)';
let config = {
type: 'line',
data: {
labels: labels,
datasets: [{
label: tempData.sensorName,
data: data,
backgroundColor: 'rgba(60,141,188,0.9)',
borderColor: posColour,
pointRadius: false,
pointColor: '#3b8bba',
pointStrokeColor: posColour,
pointHighlightFill: '#fff',
pointHighlightStroke: posColour,
segment: {
borderColor: (ctx2) => (ctx2.chart.data.datasets[0].data[ctx2.p0DataIndex] < 40 ? negColour : posColour)
}
}]
}
/* items below here are not necessary to reproduce the issue */
,
options: {
reponsive: true,
scales: {
x: {
type: 'time',
time: {
displayFormats: timeFormat,
format: 'day'
},
ticks: {
major: {
enabled: true
},
maxTicksLimit: 15
},
title: {
display: true,
text: 'Date'
}
},
y: {
title: {
display: true,
text: 'Temp (\u00b0C)'
}
}
}
}
/* items above here are not necessary to reproduce the issue */
}
我知道我可以做到非常简单地填充,但反式区域的可见影响图表不是我正在寻找的视觉效果。
我正在寻找这个答案,但是我无法完成两行(我对工作不够熟悉) Chartjs)。
let posColour= 'rgb(86,188,77)';
let negColour= 'rgb(229,66,66)';
plugins: [{
beforeRender: (x, options) => {
const c = x.chartArea; //tweaked for chart.js3
const dataset = x.data.datasets[0];
const yScale = x.scales.y; //tweaked for chart.js3
const yPos = yScale.getPixelForValue(40); //I want everything under 40 red, not 0 as the original answer...
const gradientFill = c.ctx.createLinearGradient(0, 0, 0, c.height);
gradientFill.addColorStop(0, posColour);
gradientFill.addColorStop(yPos / c.height, posColour);
gradientFill.addColorStop(yPos / c.height, negColour);
gradientFill.addColorStop(1, negColour);
//these two lines are the ones i can't figure out how to convert to chart.js3...
const model = x.data.datasets[0]._meta[Object.keys(dataset._meta)[0]].dataset._model;
model.borderColor = gradientFill;
},
}];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此答案很容易适应Chart.js v3.7.1。
请查看以下可运行的代码,然后查看其工作原理。
The solution provided by this answer can easily be adapted to also work with Chart.js v3.7.1.
Please take a look at below runnable code and see how it works.
我做出了详细的响应这里这可以为您提供帮助。
这是代码:
I have made a detailed response here that can help you.
Here is the code: