如何解决如何为chartjs散点图中的每个数据添加颜色
let dataSet = [];
Object.keys(stateData).map((item) => {
let short = {};
let medium = {};
let long = {};
if (stateData[item].horizon === "Short-term") {
short["label"] = "Short-term";
short["pointBackgroundColor"]="rgba(201,120,12,1)"
short["x"] = stateData[item].impact;
short["y"] = stateData[item].occurrence;
dataSet.push(short);
}
if (stateData[item].horizon === "Medium-term") {
medium["label"] = "Medium-Term";
medium["pointBackgroundColor"]="rgba(201,1)"
medium["x"] = stateData[item].impact;
medium["y"] = stateData[item].occurrence;
dataSet.push(medium);
}
if (stateData[item].horizon === "Long-term") {
long["label"] = "Long-Term";
long["pointBackgroundColor"]="rgba(201,1)"
long["x"] = stateData[item].impact;
long["y"] = stateData[item].occurrence;
dataSet.push(long);
}
});
const data = {
datasets: [
{
data: dataSet,}
]
};
const options = {
title: {
display: true,text: "Risks"
},scales: {
xAxes: [
{
ticks: {
max: 10,min: 0,stepSize: 0.5
}
}
],yAxes: [
{
ticks: {
max: 10,stepSize: 0.5
}
}
]
}
};
return (
<div className="w-full h-9/12">
<div className="chartjs-wrapper">
<Scatter data={data} options={options} />
</div>
</div>
);
}
上面的代码是我试图做的是使用chartjs绘制散点图并根据数据有条件地呈现点背景颜色,无论数据属于短期还是长期或中期,但我无法给出这些不同的术语有不同的颜色,任何人都可以帮我解决这个问题
解决方法
在您的 let dataSet
下放置另一个数组 let backgroundColor
,而不是在 if 中的对象中设置 pointBackgroundColor,将该颜色推入数组,然后将此数组作为 backgroundColors 添加到数据集中,这样您就可以得到这样的东西:
let dataSet = [];
let backgroundColor: [];
Object.keys(stateData).map((item) => {
let short = {};
let medium = {};
let long = {};
if (stateData[item].horizon === "Short-term") {
short["label"] = "Short-term";
backgroundColor.push("rgba(201,120,12,1)")
short["x"] = stateData[item].impact;
short["y"] = stateData[item].occurrence;
dataSet.push(short);
}
if (stateData[item].horizon === "Medium-term") {
medium["label"] = "Medium-Term";
backgroundColor.push("rgba(201,1)")
medium["x"] = stateData[item].impact;
medium["y"] = stateData[item].occurrence;
dataSet.push(medium);
}
if (stateData[item].horizon === "Long-term") {
long["label"] = "Long-Term";
.push("rgba(201,1)")
long["x"] = stateData[item].impact;
long["y"] = stateData[item].occurrence;
dataSet.push(long);
}
});
const data = {
datasets: [
{
data: dataSet,backgroundColor
}
]
};
const options = {
title: {
display: true,text: "Risks"
},scales: {
xAxes: [
{
ticks: {
max: 10,min: 0,stepSize: 0.5
}
}
],yAxes: [
{
ticks: {
max: 10,stepSize: 0.5
}
}
]
}
};
return (
<div className="w-full h-9/12">
<div className="chartjs-wrapper">
<Scatter data={data} options={options} />
</div>
</div>
);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。