Reputation: 193
R/python user, new to javascript. I am trying to do something which I thought would be simple, a basic time series chart using chart-js in react.
I don't seem to be able to get the axis to work properly, probably a really basic error but I can't seem to find any documentation on how to do this in react. My example works in regularly html/js but not in react? And the docs for react-chartjs-2 are bare bones.
I want a line chart where the X axis scales to the date (my data is unevenly spaced time series data). I think you need moment to do that but all I get is the data stacked onto 1 point (correct y values but the x values is zero for all values).
I've included a link to a minimal example in codesandbox It is based of the example in the Line example from react-chart-js.
App.tsx
import React from "react";
import "chartjs-adapter-moment";
import { Line } from "react-chartjs-2";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
} from "chart.js";
import { Chart } from "react-chartjs-2";
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
export const options = {
response: true,
scales: {
xAxes: [
{
type: "time",
time: {
unit: "day"
}
}
]
}
};
const values = [
{
x: new Date("2020-01-01"),
y: 100.2
},
{
x: new Date("2020-01-02"),
y: 102.2
},
{
x: new Date("2020-01-03"),
y: 105.3
},
{
x: new Date("2020-01-11"),
y: 104.4
}
];
export const data = {
datasets: [
{
data: values
}
]
};
export function App() {
return <Line options={options} data={data} />;
}
https://codesandbox.io/s/affectionate-hopper-uiqvz?file=/App.tsx
Upvotes: 8
Views: 7139
Reputation: 31371
This also won't work in normal is, this is because your scale config is in V2 style while you are using V3.
In v3 every scale is its own object where the key is the scale ID so there are no more arrays. Changing your config to this will make it work:
options: {
scales: {
x: {
type: 'time'
}
}
}
EDIT:
You also need to import and register the time scale and not the category scale for the x axis.
import {
Chart as ChartJS,
TimeScale, //Import timescale instead of category for X axis
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
} from "chart.js";
import { Chart } from "react-chartjs-2";
ChartJS.register(
TimeScale, //Register timescale instead of category for X axis
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
Upvotes: 11