给出这样的结构
const products = [
{
id: 1,
status: "released"
},
{
id: 2,
status: "in progress"
},
{
id: 3,
status: "in progress"
},
{
id: 4,
status: "released"
},
{
id: 5,
status: "released"
}
];
我正试图显示过去5年发布的时间线。
正如您所看到的,在上面的对象数组中,status
属性可能是不同的。因此,我的目标是在图表中显示释放对象的时间线,假设每年都与数组中的对象索引相对应。
所以,对于
数组中的第一个对象将与年份2018
匹配。
第二:2019
,
第三:2020
等。
但是,图表不应该高亮显示所有对象,而是应该有一个所有年份的标签,并且只突出显示released
的状态。
我为这样的标签创建了一个对象
const labels = ["2018", "2019", "2020", "2021", "2022"]
,
但无法在图表中实现。下面是代码示例和沙箱连接
import React from "react";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend
} from "chart.js";
import { Bar } from "react-chartjs-2";
import faker from "faker";
ChartJS.register(
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend
);
export const options = {
responsive: true,
plugins: {
legend: {
position: "top" as const
},
title: {
display: true,
text: "Chart.js Bar Chart"
}
}
};
const products = [
{
id: 1,
status: "released"
},
{
id: 2,
status: "in progress"
},
{
id: 3,
status: "in progress"
},
{
id: 4,
status: "released"
},
{
id: 5,
status: "released"
}
];
const labels = ["2018", "2019", "2020", "2021", "2022"];
export const data = {
labels,
datasets: [
{
label: "Dataset 1",
data: labels.map(() => faker.datatype.number({ min: 0, max: 1000 })),
backgroundColor: "rgba(255, 99, 132, 0.5)"
},
{
label: "Dataset 2",
data: labels.map(() => faker.datatype.number({ min: 0, max: 1000 })),
backgroundColor: "rgba(53, 162, 235, 0.5)"
}
]
};
export function App() {
return <Bar options={options} data={data} />;
}
如有任何帮助,将不胜感激。
发布于 2022-05-30 06:56:16
不确定您正在寻找的结果,但下面的代码将生成一个图表,为每年发布的条形图。
const labels = ["2018", "2019", "2020", "2021", "2022"];
export const data = {
labels,
datasets: [
{
label: "Released",
data: products.map(p => p.status === "released" ? 1:0),
backgroundColor: "rgba(255, 99, 132, 0.5)"
}
]
};
export function App() {
return <Bar options={options} data={data} />;
}
https://stackoverflow.com/questions/72436167
复制相似问题