Pandas Matplotlib';带datetime对象的axhline函数

Pandas Matplotlib';带datetime对象的axhline函数,pandas,matplotlib,python-datetime,Pandas,Matplotlib,Python Datetime,我有这样一个情节: import pandas as pd import pandas_datareader as web import datetime as dt from datetime import timedelta import matplotlib.pyplot as plt #get the data start_date = pd.to_datetime('2019-11-1') end_date = pd.datetime.today() df = web.DataRea

我有这样一个情节:

import pandas as pd
import pandas_datareader as web
import datetime as dt
from datetime import timedelta
import matplotlib.pyplot as plt

#get the data
start_date = pd.to_datetime('2019-11-1')
end_date = pd.datetime.today()
df = web.DataReader('^gspc', 'yahoo', start_date, end_date)
df = df['Adj Close']
#build the plot
fig, ax1 = plt.subplots()

ax1.plot(df)

#set the axhline
ax1.axhline(df.max(),xmin=0,xmax=1)

ax1.set_xlim(start_date,end_date + timedelta(30))
ax1.set_ylim(df.min() -200, df.max() +200)
我正在尝试设置axhline,使其从df中的最大值开始。我遇到问题,因为索引是datetime对象,axhline需要一个整数

以下是我尝试过的:

ax1.axhline(df.max(),xmin=df.idxmax(),xmax=1)
将xmin设置为df中最大值的日期的最有效方法是什么

谢谢

axhline()
使用一个y位置和两个x位置。Y在轴坐标中,x在轴坐标中(0表示左边距,1表示右边距)。但所需的起始位置仅在数据坐标中可用<代码>hlines()可以使用这些

df.argmax()
查找最大值的位置
df.index[df.argmax()]
df.idxmax()
获取该位置的索引值

将熊猫作为pd导入
将数据读取器导入web
将日期时间导入为dt
从日期时间导入时间增量
将matplotlib.pyplot作为plt导入
开始日期=pd.至日期时间('2019-11-1')
end_date=pd.datetime.today()
df=web.DataReader(“^gspc”、“yahoo”、开始日期、结束日期)
df=df['Adj Close']
图,ax1=plt.子批次()
ax1.绘图(df)
ax1.hlines(df.max(),df.idxmax(),end_date+timedelta(30),color='crimson',ls=':')
ax1.set_xlim(开始日期、结束日期+时间增量(30))
ax1.set_ylim(df.min()-200,df.max()+200)
plt.show()

ax1.plot(df)
更改为
df.plot(ax=ax1)
?使用hlines正是我所需要的。虽然我使用df.index[df.argmax()]时遇到了一个错误,但一旦我将其切换回df.idxmax(),我就得到了期望的结果。非常感谢。