J R*_*ock 4 matplotlib python-datetime pandas
我有一个看起来像这样的情节:
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)
Run Code Online (Sandbox Code Playgroud)
我正在尝试设置 axhline,以便它从 df 中最大值的那一天开始。我遇到问题,因为索引是日期时间对象,而 axhline 需要一个整数。
这是我尝试过的:
ax1.axhline(df.max(),xmin=df.idxmax(),xmax=1)
Run Code Online (Sandbox Code Playgroud)
将 xmin 设置为 df 中最大值的日期的最有效方法是什么?
谢谢
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()
Run Code Online (Sandbox Code Playgroud)