chartjs-plugin-zoom
chartjs-plugin-zoom copied to clipboard
Adding max limit prevents pan
I'm adding chartjs-plugin-zoom to my project, I need to pan on x axis but when I add limits (max), pan doesn't work. The whole chart is fixed and doesn't pan left/right
My codesandbox: https://codesandbox.io/embed/competent-pine-lgtijw?fontsize=14&hidenavigation=1&theme=dark
Screenshot ( as you can see all the data is displayed at once on the chart)
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";
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
},
limits: {
x: { min: "original", max: "original" }
}
}
}
};
const data = {
datasets: [
{
data: [
{ x: 1672549200000, y: 10 },
{ x: 1672635600000, y: 20 },
{ x: 1672808400000, y: 20 },
{ x: 1675061057000, y: 20 }
]
}
]
};
const canvasRef = useRef();
return (
<div className="App">
<Bar
ref={canvasRef}
options={options}
data={data}
height={null}
width={null}
/>
</div>
);
}
How can I fix the chart so it pans from first ms till last ms ( without displaying all dates at once). If I don't add limits, then x Axis displays dates(ms) that haven't been specified in the data options.
Panning is if you set the range to show Jan 2-5, and then you want to move that view to earlier and later (continuing to only show the span of 3 days, for example).
It sounds like you want to skip the x-axis dates that don't have data points. That's a general chart.js question. Can't use spanGaps, since that's for line charts.
It sounds like you want something like:
options.scales.x.type = "timeseries" options.scales.x.ticks.source = "data"
The source = "data" removes the x-axis dates with no data points, and type = "timeseries" makes it look better.