I'm adding Chart js to my React project where I need to display data per day, everything seems to be working fine, except when I add pan functionality, the chart scrolls left/right and adds some random dates. for example this is the data I want to display:
data: [
{ x: "2021-01-01", y: 10 },
{ x: "2021-01-02", y: 20 },
{ x: "2021-01-03", y: 20 },
{ x: "2021-01-04", y: 20 },
{ x: "2021-01-05", y: 20 }
]
this is how chart looks if I scroll left
I don't understand where Dec 31 is coming from, also if I scroll to the right, I'm getting additional days that are not defined in the data( January 6, 7 etc). How can I restrict the pan to scroll according to the provided date range only? ( don't pan to Dec 31 or January 6)
My code in codesandbox
My code:
import "./styles.css";
import { Bar } from "react-chartjs-2";
import {
Chart as ChartJS,
CategoryScale,
Title,
LinearScale,
PointElement,
Tooltip,
Legend,
TimeScale,
BarElement
} from "chart.js";
import "chartjs-adapter-date-fns";
import { enUS } from "date-fns/locale";
ChartJS.register(
BarElement,
CategoryScale,
LinearScale,
Title,
Tooltip,
Legend,
zoomPlugin,
TimeScale
);
import zoomPlugin from "chartjs-plugin-zoom";
import { useRef } from "react";
export default function App() {
const options = {
maintainAspectRatio: false,
responsive: true,
elements: {
point: {
radius: 0
},
line: {
borderWidth: 1.5
}
},
scales: {
x: {
type: "time",
time: {
unit: "day"
},
ticks: {
color: "rgba( 0, 0, 1)"
},
grid: {
color: "rgba(0, 0, 0, 1)"
}
},
y: {
ticks: {
color: "rgba(0, 0, 0, 1)"
},
grid: {
color: "rgba(0, 0, 0, 1)"
}
}
},
plugins: {
zoom: {
pan: {
enabled: true,
mode: "x",
speed: 10
}
}
}
};
const data = {
datasets: [
{
data: [
{ x: "2021-01-01", y: 10 },
{ x: "2021-01-02", y: 20 },
{ x: "2021-01-03", y: 20 },
{ x: "2021-01-04", y: 20 },
{ x: "2021-01-05", y: 20 }
]
}
]
};
const canvasRef = useRef();
return (
<div className="App">
<Bar
ref={canvasRef}
options={options}
data={data}
height={null}
width={null}
/>
</div>
);
}
from How to limit chart js to display existing axis values?
No comments:
Post a Comment