Blog>
Snippets

Creating a Time-Series Chart for Environmental Data

Demonstrate how to format and display environmental data, such as temperature over time, using a time-series chart with TanStack React Charts.
import { Chart } from 'react-chartjs-2';
import 'chart.js/auto';
First, import the Chart component from react-chartjs-2 and automatically register the required chart types and controllers from chart.js.
const data = {
  labels: ['January', 'February', 'March', 'April'],
  datasets: [{
    label: 'Average Temperature (°C)',
    data: [3, 6, 9, 12],
    fill: false,
    borderColor: 'rgb(75, 192, 192)',
    tension: 0.1
  }]
};
Define the data object, including the time labels (e.g., months) and the dataset for temperatures with styling.
const options = {
  scales: {
    x: {
      type: 'time',
      time: {
        unit: 'month'
      }
    }
  }
};
Configure chart options, specifying a time scale for the x-axis to correctly display time series data.
const TimeSeriesChart = () => (
  <Chart
    type='line'
    data={data}
    options={options}
  />
);
Create the TimeSeriesChart component that renders a line chart using the Chart component, passing the data and options.
export default TimeSeriesChart;
Export the TimeSeriesChart component for use in other parts of your application.