How to use type: 'time' for line chart in chart.js?

42 Views Asked by At

With one item in the data, y axis shows proper number.

Nothing shows up in the chart. It shows only x and y axis, but nothing inside the chart. What needs to be done to display data in the chart?

When I add second item in the data, y axis changes and shows 0 to 1. Why is this happening?


import Chart from 'chart.js/auto'
import 'chartjs-adapter-date-fns';

const timeScaleChart = () => {
  const data = [
    { year: "2022-05-01", count: 30, borderColor: "red", backgroundColor: 'blue' },
    { year: "2026-05-01", count: 40, borderColor: "red", backgroundColor: 'blue' },
  ];

  new Chart(
    document.getElementById('timeline'),
    {
      type: 'line',
      options: {
        plugins: {
          title: {
            text: 'Chart.js Time Scale',
            display: true
          }
        },
        scales: {
          x: {
            type: 'time',
            time: {
              unit: 'day'
            },
            title: {
              display: true,
              text: 'Date'
            }
          },
          y: {
            title: {
              display: true,
              text: 'count'
            }
          }
        },
      },
      data: {
      labels: data.map(row => row.year),
        datasets: [
          {
            label: 'Time scale',
            data: [{
              x: data.map(row => row.year),
              y: data.map(row => row.count),
            }],
            borderColor: data.map(row => row.borderColor),
            backgroundColor: data.map(row => row.backgroundColor),
            fill: false,
          }
        ]
      }
    }
  );
};

export default timeScaleChart;
1

There are 1 best solutions below

0
user7331530 On

I needed to transform the data.

const transformedData = data.map(({ year, count }) => ({ x: year, y: count }));

and use it data: transformedData