javascriptreactjschartschart.jsfreshjs

Chart.js - How to generate time chart


I'm making a simple server log, and I want to use Chart.js to generate total hit reports by hour, day, month, or year. Here is my code:

import { ChartColors } from "$fresh_charts/utils.ts";
import Chart from "../../islands/chart.tsx";

const data = [
  { x: "2016-12-25", y: 20 },
  { x: "2017-12-26", y: 10 },
  { x: "2020-12-26", y: 10 },
  { x: "2024-12-26", y: 10 },
]
export default function ChartPage(props) {
  return (
    <div class="p-4 mx-auto max-w-screen-md">
      <Chart
        type="line"
        options={{
          scales: {
            x: {
              type: "time",
              time: {
                "unit": "year",
              },
              displayFormats: {
                "year": "YYYY",
              },
            },
            y: { beginAtZero: true },
          },
        }}
        data={{
          datasets: [
            {
              label: "Users",
              data: data,
              borderColor: ChartColors.Blue,
              borderWidth: 1,
            },
          ],
        }}
      />
    </div>
  );
}

If I comment out the x-scale option totally, then the chart is generated fine (though incorrectly in scale). If I keep the x-scale option, then it cannot be rendered. I know I misconfigured something in Time Cartesian Axis, but I cannot figure it out. How to make this work?


Solution

  • I believe that you are not installing and importing the Date Adapter library.

    1. Install the date adapter library.
    {
      ...,
      "dependencies": {
        "react": "^18.2.0",
        "react-dom": "^18.2.0",
        "chart.js": "^4.4.2",
        "chartjs-adapter-moment": "^1.0.0"
      },
      ...
    }
    
    1. Importing the date adapter library in chart.tsx
    import 'chartjs-adapter-moment';
    

    Demo @ StackBlitz