我正在使用 AmCharts 显示多行。我的
chartData
是每日数据,其中 x
作为 Unix 时间戳(以秒为单位):
{
line1: [{x: UNIX_TIMESTAMP_SECONDS, y: NUMERICAL_VALUE}, ... ]
line2: [{x: UNIX_TIMESTAMP_SECONDS, y: NUMERICAL_VALUE}, ... ]
}
我的图表组件:
const AmChart = (chartData) => {
useLayoutEffect(() => {
const root = am5.Root.new("chartdiv");
const chart = root.container.children.push(
am5xy.XYChart.new(root, {})
);
const yAxis = chart.yAxes.push(
am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {})
})
);
const xAxis = chart.xAxes.push(
am5xy.DateAxis.new(root, {
baseInterval: { timeUnit: "second", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {}),
gridIntervals: [
{ timeUnit: "day", count: 1 },
{ timeUnit: "month", count: 1 },
{ timeUnit: "year", count: 1 }
],
})
);
Object.entries(chartData).map(([key, value]) => {
const series = chart.series.push(
am5xy.LineSeries.new(root, {
name: key,
xAxis,
yAxis,
valueXField: "x",
valueYField: "y",
})
);
series.data.setAll(value);
return null
});
return () => {
root.dispose();
};
}, []);
return (
<div id="chartdiv" />
);
}
图表数据显示正确,但无论缩放级别如何,x 轴都只有一个刻度。所以我的 x 轴配置有一些不正确的地方,这是我从 documentation:
得到的const xAxis = chart.xAxes.push(
am5xy.DateAxis.new(root, {
baseInterval: { timeUnit: "second", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {}),
gridIntervals: [
{ timeUnit: "day", count: 1 },
{ timeUnit: "month", count: 1 },
{ timeUnit: "year", count: 1 }
],
})
);
如果我删除
gridIntervals
项目,x 轴刻度恢复正常,但显示为 HH:MM:SS,鉴于我的数据是每日数据,这是不合适的。
如何以每日格式显示 x 轴刻度?
AmCharts 期望 UNIX 时间戳以毫秒为单位,这有点隐藏在 docs 中。只需使用现有的图表数据并将时间戳乘以 1000,然后将
baseInterval
设置为天:
const xAxis = chart.xAxes.push(
am5xy.DateAxis.new(root, {
baseInterval: { timeUnit: "days", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {}),
})
);
仅当您想根据缩放覆盖月/周/日等之间的默认动态切换时,才需要
gridIntervals
参数。