'Datetime Objects on X-axis with matplotlib
I'm plotting some data using matplotlib with DateTime objects on the x-axis, but can't seem to figure out why my DateTime values aren't spaced out on the x-axis according to their values. For example, I might have values recorded at 2022-04-21 03:59:30, and 2022-04-21 04:02:20 - but the distance between these two values on the x-axis would be the same as the distance between 2022-04-21 04:02:26 and 2022-04-21 04:06:54; there's a difference of nearly 3 mintues between the former pair, and just 6 seconds between the latter pair - yet the scale is the same. (See attached image)
In short, how do I make the scale on the x-axis with DateTime values more realistic when plotting with matplotlib?
Solution 1:[1]
You are plotting just 4 points, so Matplotlib equally distributes them on the x axis, that has just 4 points.
To reach your goal you need to "manually" define the x axis. For example:
from datetime import datetime
import numpy as np
from datetime import timedelta
x_start = datetime.strptime('2022-04-21 03:59:30', "%Y-%m-%d %H:%M:%S")
x_end = datetime.strptime('2022-04-21 04:51:49', "%Y-%m-%d %H:%M:%S")
timestamps = np.arange(x_start, x_end, timedelta(minutes=1), dtype=datetime)
x_axis = [timestamp.strftime("%Y-%m-%d %H:%M") for timestamp in timestamps]
In this way the x axis has 53 points, one for each minute from 03:59 from 04:51. You can change the "step" of the x axis changing timedelta(minutes=1) when you define timestamps
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nicc96 |
