I am making a chart displaying stock data using ChartJs (react-chartjs-2). I have a datapoint for every minute from 9:30am to 3:59pm. When I plot it, my chart looks like the image below. The points don't even remotely align with the grid. The point in the image says 10:16 but the chart positions it between 9 and 10. Why is it like this? The points should also start halfway after the 9 tick since my data starts at 9:30. Does anyone know what I can do to resolve this?
My data is in the format like x = 2023-02-15 09:30:00-05:00
and y = 226.145
. I have an option that truncates what is displayed on the tick so instead of displaying the entire datetime format, it only displays the hour.
Here is some of my code:
const data = {
labels: Object.keys(stockdata),
datasets: [
{
data: Object.values(stockdata),
borderColor: "rgba(75,192,192,1)",
},
],
};
const options = {
responsive: true,
plugins: {
legend: {
position: "top",
},
title: {
display: true,
text: "Chart.js Line Chart",
},
},
pointRadius: 0,
scales: {
x: {
ticks: {
callback: function (val) {
const time = parseInt(
this.getLabelForValue(val).split(" ")[1].split(":")[0] % 12
);
return time == 0 ? 12 : time;
},
maxTicksLimit: 7,
},
grid: {
color: "#303030",
},
},
y: {
grid: {
color: "#303030",
},
},
},
};
React component render:
<Line data={data} options={options} />
I assume the issue is, that your localtime has a date offset off -1 hours, but without seeing the data (and knowing the offset), I can't say for sure.
If this would be the case, you could/would have to convert your dataset values. Depending on your dataset and available libraries you could use functions like:
momentjs:
let localDate= moment.utc("2023-02-01 10:00:00")
.local()
.format("YYYY-MM-DD HH:mm:ss");
vanilajs:
let localDate = new Date(Date.UTC(2023, 1, 1, 10, 0, 0));
You would have to loop through all the x-values / dates entries, to fix this.