I made a custom chartjs component in reactjs and want to render dates in xAxes and numbers from -1 to 1 in yAxes but it renders data not in a proper way.
import React, { useRef, useEffect } from "react";
import Chart from "chart.js";
const ChartComponent = ({ data, label, min, max }) => {
const canvasRef = useRef(null);
useEffect(() => {
const canvasObj = canvasRef.current;
const context = canvasObj.getContext("2d");
new Chart(context, {
type: "line",
data: {
datasets: [
{
label: label,
backgroundColor: "transparent",
data: data,
},
],
},
options: {
scales: {
xAxes: [
{
type: "time",
distribution: "linear",
time: {
unit: "month",
displayFormats: {
quarter: "YYYY mm dd",
},
},
},
],
yAxes: [
{
ticks: {
suggestedMax: max,
suggestedMin: min,
},
},
],
},
},
});
}, [data, label, min, max]);
return <canvas ref={canvasRef}> </canvas>;
};
export default ChartComponent;
and I'm passing the data like this to the component
<ChartComponent
min={-1}
max={1}
label="date"
data={[
{
x: "30/03/2018",
y: 0.1158,
},
{
x: "24/09/2018",
y: 0.1975,
},
{
x: "23/12/2018",
y: 0.1913,
},
{
x: "23/03/2019",
y: 0.2137,
},
]}
/>;
I have to metion that I have done the same thing and that is working alright this is example below
<ChartComponent
min={1270}
max={1272}
label=" مساحت دریاچه"
data={[
{
x: "04/02/2017",
y: 1270.7,
},
{
x: "06/26/2017",
y: 1270.74,
},
{
x: "09/19/2017",
y: 1270.31,
},
{
x: "12/18/2017",
y: 1270.28,
},
{
x: "06/16/2018",
y: 1270.81,
},
{
x: "09/24/2018",
y: 1270.27,
},
{
x: "12/23/2018",
y: 1270.54,
},
{
x: "05/25/2019",
y: 1271.94,
},
{
x: "06/18/2019",
y: 1271.84,
},
{
x: "09/19/2019",
y: 1271.31,
},
{
x: "12/18/2019",
y: 1271.25,
},
{
x: "03/12/2020",
y: 1271.48,
},
{
x: "06/25/2020",
y: 1271.72,
},
]}
/>;
any recommendation would be appreciated. thank you.
The problem is that the date strings you provide are not of ISO 08601 nor RFC 2822 Date time format, hence they cannot be parsed by Moment.js, which is internally used by Chart.js.
To make it work, you have to define xAxes.time.parser: "DD.MM.YYYY"
.
Please take a look at below runnable code and see how it works. This is pure JavaScript example but it should also work with react-chartjs-2
.
new Chart("myChart", {
type: "line",
data: {
datasets: [{
label: 'My Dataset',
data: [
{ x: "30/03/2018", y: 0.1158 },
{ x: "24/09/2018", y: -0.1975 },
{ x: "23/12/2018", y: 0.1913 },
{ x: "23/03/2019", y: -0.2137 }
],
fill: false
}]
},
options: {
scales: {
xAxes: [{
type: "time",
time: {
parser: "DD.MM.YYYY",
unit: "month",
displayFormats: {
month: "YYYY MM DD",
}
}
}],
yAxes: [{
ticks: {
suggestedMax: 1,
suggestedMin: -1
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
<canvas id="myChart" height="100"></canvas>
As I already mentioned, Chart.js internally uses Moment.js for the functionality of the time axis. Therefore make sure to use the bundled version of Chart.js that includes Moment.js in a single file.