Search code examples
chart.jsreact-chartjs-2luxon

Chartjs sample can't be reproduced


I am looking to reproduce the result of this sample from Chartjs doc : https://www.chartjs.org/docs/latest/samples/scales/time-line.html

What I am looking for is the scale result on x : enter image description here

I use react with react-chartjs-2 and a simplified version of the example, but I managed to keep same config and data for the x axis :

import { DateTime } from 'luxon';
import { Line } from 'react-chartjs-2';
import { Chart as ChartJS, registerables } from 'chart.js';
import 'chartjs-adapter-luxon';

ChartJS.register(...registerables);

function newDate(days: number) {
  return DateTime.now().plus({ days }).toJSDate();
}

function newDateString(days: number) {
  return DateTime.now().plus({ days }).toISO();
}

const options = {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: { display: false },
  },
  scale: {
    x: {
      type: 'time',
      time: {
        tooltipFormat: 'DD T',
      },
    },
    y: {
      type: 'linear',
      suggestedMin: 0,
      suggestedMax: 100,
      ticks: {
        stepSize: 20,
      },
    },
  },
};

const labels = [newDate(0), newDate(1), newDate(2), newDate(3), newDate(4), newDate(5), newDate(6)];
const Data = [
  {
    x: newDateString(0),
    y: 41,
  },
  {
    x: newDateString(5),
    y: 21,
  },
  {
    x: newDateString(7),
    y: 12,
  },
  {
    x: newDateString(15),
    y: 38,
  },
];

/*...*/
<Line
  options={options}
  data={{
     datasets: [{ data: data }],
       labels: labels,
     }}
/>

I got the following result (not even close from sample) enter image description here

Thanks you


Solution

  • Your problem is in your options, the scale configs never get applied since you defined the options for the scales in the scale key while they have to be defined in the scales key, note the extra s