我正在使用 ChartJS/react-chartjs-2 创建条形图。 到目前为止,条形图显示正常,没有什么特别的:
我的数据如下所示:
{
Name: "De Regenboog",
Patients: "7546",
Year1Total: "34",
Year1Pos: "4",
Year2Total: "51",
Year2Pos: "1",
Year3Total: "43",
Year3Pos: "0",
},
{
Name: "George Michael",
Patients: "2644",
Year1Total: "20",
Year1Pos: "0",
Year2Total: "18",
Year2Pos: "0",
Year3Total: "64",
Year3Pos: "0",
},
etc
]
我希望积极因素显示为该名称当年总栏的一部分。 因此,对于 2021 年的“De Regenboog”,它将显示总条数为 34,并且 4 条的颜色将与当年的阳性测试不同。我不知道要搜索什么或如何解决这个问题。这可能吗?也许有人有想法?
您可以为每个数据集条目设置背景颜色,以在同一栏中的正例和其余总数之间创建视觉区别,因此,如果您的数据如下所示:
const dataSet = [
{
Name: "De Regenboog",
Patients: "7546",
Year1Total: "34",
Year1Pos: "4",
Year2Total: "51",
Year2Pos: "1",
Year3Total: "43",
Year3Pos: "0",
},
{
Name: "George Michael",
Patients: "2644",
Year1Total: "20",
Year1Pos: "0",
Year2Total: "18",
Year2Pos: "0",
Year3Total: "64",
Year3Pos: "0",
},
etc
];
您可以用不同的颜色标记数据集条目,如下所示:
const data = {
labels: dataSet.map(entry => entry.Name),
datasets: [
{
label: 'Year1 Positives',
data: dataSet.map(entry => parseInt(entry.Year1Pos)),
backgroundColor: 'rgba(255, 99, 132, 0.5)',
},
{
label: 'Year1 Total Minus Positives',
data: dataSet.map(entry => parseInt(entry.Year1Total) - parseInt(entry.Year1Pos)),
backgroundColor: 'rgba(54, 162, 235, 0.5)',
},
{
label: 'Year2 Positives',
data: dataSet.map(entry => parseInt(entry.Year2Pos)),
backgroundColor: 'rgba(255, 206, 86, 0.5)',
},
{
label: 'Year2 Total Minus Positives',
data: dataSet.map(entry => parseInt(entry.Year2Total) - parseInt(entry.Year2Pos)),
backgroundColor: 'rgba(75, 192, 192, 0.5)',
},
{
label: 'Year3 Positives',
data: dataSet.map(entry => parseInt(entry.Year3Pos)),
backgroundColor: 'rgba(153, 102, 255, 0.5)',
},
{
label: 'Year3 Total Minus Positives',
data: dataSet.map(entry => parseInt(entry.Year3Total) - parseInt(entry.Year3Pos)),
backgroundColor: 'rgba(255, 159, 64, 0.5)',
},
],
};
注意:如果名称不同,请确保将“dataSet”更改为数据集名称。