Blog>
Snippets

Line Chart with Time-Scale Axis

Code example on setting up a line chart with a time-scale x-axis to represent time series data effectively, including formatting date labels for clarity.
import { Line } from 'react-chartjs-2';
import 'chart.js/auto';

const data = {
  datasets: [
    {
      label: 'Time Series Data',
      data: [
        { x: '2023-04-01', y: 1 },
        { x: '2023-04-02', y: 2 },
        { x: '2023-04-03', y: 3 },
        // Add more data points here
      ],
      fill: false,
      borderColor: 'rgb(75, 192, 192)',
      tension: 0.1
    }
  ]
};

const options = {
  scales: {
    x: {
      type: 'time',
      time: {
        unit: 'day',
        displayFormats: {
           day: 'MMM D'
        }
      },
      title: {
        display: true,
        text: 'Date'
      }
    },
    y: {
      title: {
        display: true,
        text: 'Value'
      }
    }
  },
  plugins: {
    legend: {
      display: true,
      position: 'top',
    }
  }
};
This code sets up a line chart with a time-scale x-axis using react-chartjs-2. It imports necessary modules, defines the data with x values as date strings and y values as numerical data. The options configure the x-axis as a time scale with daily units and custom date display formats. It also sets titles for both axes and displays a legend on top.
return <Line data={data} options={options} />;
This line renders the line chart in a React component using the 'data' and 'options' objects defined previously. It utilizes the Line component from react-chartjs-2 library.