colors - 图表JS根据数据值改变pointBackgroundColor
问题描述
所以我使用 Chartjs 创建了一个基本的折线图。我将如何根据数据的值更改点的颜色(pointBackgroundColor)?例如,如果数据点小于 10 则变为红色,或者如果数据点在 10 到 20 之间则变为蓝色?
const CHART = document.getElementById("lineChart");
let lineChart = new Chart(CHART, {
type: 'line',
data: {
labels: ["5/10/2010", "5/11/2010", "5/12/2010", "5/13/2010", "5/14/2010", "5/15/2010", "5/16/2010"],
datasets: [
{
label: "Theta",
fill: false,
lineTension: 0,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(9,31,62)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(0,191,255)",
pointBackgroundColor: "rgba(0,191,255)",
pointBorderWidth: 5,
pointBorderRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [15, 28, 11, 3, 34, 65, 20],
}
]
},
options: {
maintainAspectRatio: false,
responsive: true,
legend: {
display: false,
},
scales: {
yAxes:[{
ticks: {
fontColor: "#091F3e",
beginAtZero: true,
steps: 10,
stepSize: 10,
max: 100
},
gridLines: {
display: false
}
}],
xAxes:[{
ticks: {
fontColor: "#091F3e",
fontSize: "10",
},
gridLines: {
display: false
}
}]
}
}
});
解决方案
您可以在任何选项上使用闭包并根据上下文操作返回的值。pointBackgroundColor
在下面的示例中,当当前值大于 0 时,我是红色的,否则是蓝色的。
pointBackgroundColor: function (context) {
let value = context.dataset.data[context.dataIndex];
return value > 0
? 'red'
: 'blue';
},
推荐阅读
- android - 登录屏幕上的 EditText 验证
- php - Laravel如何生成六个不同整数的随机用户ID
- r - R:调试 Plotly 代码 - 找不到对象(时间序列分析)
- c - QMK RGB 饱和度触底
- amazon-web-services - 如果我已经拥有我的私有证书,我是否需要 AWS 的证书颁发机构?
- terraform - 如何在 terraform 中正确使用 for_each 中的 each.value?
- python-3.x - 如何使用 tensorflow 2 模型动物园在自定义对象检测器中创建检查点?
- javascript - 将组件的结果传递给渲染返回未定义?
- flexbox - 嵌套在部分类中的 DIV 类未设置为显示:flex
- javascript - 如果未单击任何复选框,则禁用按钮