数据中只有一项,y 轴显示正确的数字。
图表中没有显示任何内容。它仅显示 x 和 y 轴,但图表内不显示任何内容。需要做什么才能在图表中显示数据?
当我在数据中添加第二项时,y 轴发生变化并显示 0 到 1。为什么会发生这种情况?
import Chart from 'chart.js/auto'
import 'chartjs-adapter-date-fns';
const timeScaleChart = () => {
const data = [
{ year: "2022-05-01", count: 30, borderColor: "red", backgroundColor: 'blue' },
{ year: "2026-05-01", count: 40, borderColor: "red", backgroundColor: 'blue' },
];
new Chart(
document.getElementById('timeline'),
{
type: 'line',
options: {
plugins: {
title: {
text: 'Chart.js Time Scale',
display: true
}
},
scales: {
x: {
type: 'time',
time: {
unit: 'day'
},
title: {
display: true,
text: 'Date'
}
},
y: {
title: {
display: true,
text: 'count'
}
}
},
},
data: {
labels: data.map(row => row.year),
datasets: [
{
label: 'Time scale',
data: [{
x: data.map(row => row.year),
y: data.map(row => row.count),
}],
borderColor: data.map(row => row.borderColor),
backgroundColor: data.map(row => row.backgroundColor),
fill: false,
}
]
}
}
);
};
export default timeScaleChart;
我需要转换数据。
const transformedData = data.map(({ year, count }) => ({ x: year, y: count }));
并使用它
data: transformedData