Matplotlib的axhline函数如何使用datetime对象?

4

我有一个类似这样的图:

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中最大值日期?

谢谢。


ax1.plot(df) 改为 df.plot(ax=ax1) - Quang Hoang
1个回答

5

axhline()使用一个y位置和两个x位置,其中y在数据坐标系中,而x在轴坐标系中(左侧边距为0,右侧边距为1)。但是所需的起始位置仅在数据坐标系中可用。hlines()可以处理这些。

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

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

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']

fig, ax1 = plt.subplots()
ax1.plot(df)
ax1.hlines(df.max(), df.idxmax(), end_date + timedelta(30), color='crimson', ls=':')
ax1.set_xlim(start_date, end_date + timedelta(30))
ax1.set_ylim(df.min() - 200, df.max() + 200)
plt.show()

example plot


使用 hlines 正是我所需要的。不过我在使用 df.index[df.argmax()] 时遇到了错误,但一旦我切换回 df.idxmax(),我就得到了想要的结果。谢谢! - J Rock

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接