Matplotlib 的带有日期时间对象的 axhline 函数
Matplotlib's axhline function with a datetime object
我有一个看起来像这样的情节:
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 中最大值的日期的最有效方法是什么?
谢谢
axhline()
使用一个 y 位置和两个 x 位置。 Y 在 data coordinates 中,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()
我有一个看起来像这样的情节:
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 中最大值的日期的最有效方法是什么?
谢谢
axhline()
使用一个 y 位置和两个 x 位置。 Y 在 data coordinates 中,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()