pandas - 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 中最大值的日期的最有效方法是什么?
谢谢
解决方案
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()
推荐阅读
- swift - 无法在 Swift 中保存 Bool
- mysql - 在 MySQL 中使用 SUM 和连接返回意外结果
- scala - 在火花流中聚合后努力处理重复数据删除
- chronicle - 将消息刷新到 Chronicle Queue
- javascript - 有没有办法改变锚的行为?
- flask - Celery CRITICAL/MainProcess] 不可恢复的错误:AttributeError("'float' object has no attribute 'items'",)
- java - HTTPS 连接不安全
- clojure - 如何在 lein 项目中编译不在“src”下的 clojure 模块
- javascript - 点击事件绑定的奇怪行为;事件未触发
- c++ - 从文件夹中多次读取