Suppose we have the following dataframe and we have a local maximum after 2 pm. How can we use a horizontal line segment that is limited within 15 minutes from the actual point?
fig, ax = plt.subplots(figsize=(20, 4))
index = pd.date_range('7-20-2022', '7-21-2022', freq='min')
np.random.seed(0)
df = pd.DataFrame(np.cumsum(np.random.randn(len(index))), index=index)
df_limited = df.loc['7-20-2022'].between_time('14:00', '15:00')
idx = df_limited.idxmax()
max = df_limited.loc[idx]
df.plot(ax=ax)
ax.axhline(max.values, color='r', xmin=0.57, xmax=0.6)
plt.show()
Currently, the local maximizer is at 2022-07-20 14:06:00
and max is at -46.80
, I want to plot a horizontal line from 13:51-14:21
where 14:06
is at the center. My solution is hard coded and I do not know how I can get xmin
or xmax
if I change 15 minutes to 20 minutes, also, I do not know if the position of max changes, how I can get the associated xmin
and xmax
?
Question
Write a function that takes idx
, delta time dt
, i.e., 15 minutes and returns xmin
and xmax
that is suited for the x-axis which is indexed by the DateTimeIndex
.
CodePudding user response:
You can use hlines
instead of axhline
to use datetime index:
offset = pd.Timedelta('15T')
ax.hlines(max.values, xmin=max.index[0]-offset, xmax=max.index[0] offset, color='r')
Output: