首页 > 解决方案 > Matplotlib 的 axhline 函数与日期时间对象

问题描述

我有一个看起来像这样的情节:

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 中最大值的那一天开始。我遇到了问题,因为索引是一个日期时间对象,而 axhline 需要一个整数。

这是我尝试过的:

ax1.axhline(df.max(),xmin=df.idxmax(),xmax=1)

将 xmin 设置为 df 中最大值的日期的最有效方法是什么?

谢谢

标签: pandasmatplotlibpython-datetime

解决方案


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()

示例图


推荐阅读