0

I try to display a matplotlib.patches.Rectangle over a pyplot. My X-axis is of format datetime64. It spans over ~10hours and I'd like my Rectangle to have a width of 10 minutes. It shall be centered on event Date_hour value.

In [1]: print(events['Date_hour'].values[1])
Out [1]: ['2022-05-12T16:32:58.000000000']
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# Rectangle width
width = np.timedelta64(10, 'm')

# Create rectangle
events_patches = [Rectangle(xy=[event['Date_hour'].values[1]-width/2, 0], width=width, height=10]
pc = PatchCollection(events_patches)
ax.add_collection(pc)

ax.plot(data['Date_hour'].values[:,0], data['var1'].values[:,0])

fig.savefig('./test.png')

It throws the following error:

Traceback (most recent call last):
........
........
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/axis.py", line 1190, in _update_ticks
    major_locs = self.get_majorticklocs()
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/axis.py", line 1416, in get_majorticklocs
    return self.major.locator()
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/dates.py", line 1366, in __call__
    dmin, dmax = self.viewlim_to_dt()
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/dates.py", line 1151, in viewlim_to_dt
    return num2date(vmin, self.tz), num2date(vmax, self.tz)
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/dates.py", line 533, in num2date
    return _from_ordinalf_np_vectorized(x, tz).tolist()
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/numpy/lib/function_base.py", line 2328, in __call__
    return self._vectorize_call(func=func, args=vargs)
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/numpy/lib/function_base.py", line 2411, in _vectorize_call
    outputs = ufunc(*inputs)
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/dates.py", line 354, in _from_ordinalf
    np.timedelta64(int(np.round(x * MUSECONDS_PER_DAY)), 'us'))
OverflowError: int too big to convert
  • Found my solution here: https://stackoverflow.com/questions/31162780/how-to-plot-a-rectangle-on-a-datetime-axis-using-matplotlib – v_for_vantouza Dec 15 '22 at 11:03

0 Answers0