javascriptreactjschartsamchartsamcharts5

AmCharts DateAxis not using specified intervals


I'm using AmCharts to display multiple lines. My chartData is daily data with x as the Unix Timestamp in seconds:

{
  line1: [{x: UNIX_TIMESTAMP_SECONDS, y: NUMERICAL_VALUE}, ... ]
  line2: [{x: UNIX_TIMESTAMP_SECONDS, y: NUMERICAL_VALUE}, ... ]
}

My chart component:

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" />
  );
}

The chart data displays correctly, but the x-axis only has a single tick regardless of zoom level. So there is something incorrect about my x-axis config, which I got from the 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 }
    ],
  })
);

If I remove the gridIntervals item, the x-axis ticks return to normal but they are displayed as HH:MM:SS, which is not appropriate given my data is daily.

How can I show my x-axis ticks in a daily format?


Solution

  • AmCharts expects UNIX timestamps in milliseconds, which is a bit hidden in the docs. Simply take your existing chartData and multiply the timestamps by 1000, then set your baseInterval to days:

    const xAxis = chart.xAxes.push(
      am5xy.DateAxis.new(root, {
        baseInterval: { timeUnit: "days", count: 1 },
        renderer: am5xy.AxisRendererX.new(root, {}),
      })
    );
    

    The gridIntervals parameter is only needed if you want to override the default dynamic switching between month/week/day etc. depending on zoom.