在 pandas df 中向时间序列图添加垂直线
Adding a vertical line to a time series plot in pandas df
我使用这个问题的答案来尝试在我的时间序列图中添加一条垂直线:How do you plot a vertical line on a time series plot in Pandas?
这是我的代码:
ax = df.plot(figsize=(12,8), logy=True, title='Random Forest Regressor Performance',\
color={'price': 'blue', 'count': 'orange', 'pred': 'green'})
ax.axvline(pd.to_datetime('2021-08-23'), color='r', linestyle='--', lw=2)
这是我的数据(我将日期(日期时间)设置为索引):
date
price
pred
count
2018-01-01
13657.20
12671.454
89709
2018-01-02
14982.10
18561.360
125144
2018-01-03
15201.00
14437.636
134138
...
...
...
...
2021-10-30
61888.10
39418.360
283597
2021-10-31
61318.00
34461.636
312403
在我的例子中,使用这种方法会导致行被放置在实际数据之外。这个想法是把线放到这张图上。我得到的:
预期结果:
我假设 pandas 没有将轴格式设置为日期时间,而是将日期时间值转换为数字并更改刻度标签。显式创建轴并设置正确的格式有效。
在此之后,下面的最小示例显示了如何设置轴的日期时间格式并使用相应的日期时间字符串添加 hline。
import matplotlib.pyplot as plt
import pandas as pd
times = pd.date_range('2021-12-07', periods=500, freq='D')
yvalues = range(times.size)
df = pd.DataFrame(yvalues, times)
fig, ax = plt.subplots(1)
fig.autofmt_xdate()
ax.axvline(pd.to_datetime('2023-01-23'), color='r', linestyle='--', lw=2)
ax = df.plot(ax=ax, title='Random Forest Regressor Performance')
plt.show()
这导致 plot
我使用这个问题的答案来尝试在我的时间序列图中添加一条垂直线:How do you plot a vertical line on a time series plot in Pandas?
这是我的代码:
ax = df.plot(figsize=(12,8), logy=True, title='Random Forest Regressor Performance',\
color={'price': 'blue', 'count': 'orange', 'pred': 'green'})
ax.axvline(pd.to_datetime('2021-08-23'), color='r', linestyle='--', lw=2)
这是我的数据(我将日期(日期时间)设置为索引):
date | price | pred | count |
---|---|---|---|
2018-01-01 | 13657.20 | 12671.454 | 89709 |
2018-01-02 | 14982.10 | 18561.360 | 125144 |
2018-01-03 | 15201.00 | 14437.636 | 134138 |
... | ... | ... | ... |
2021-10-30 | 61888.10 | 39418.360 | 283597 |
2021-10-31 | 61318.00 | 34461.636 | 312403 |
在我的例子中,使用这种方法会导致行被放置在实际数据之外。这个想法是把线放到这张图上。我得到的:
预期结果:
我假设 pandas 没有将轴格式设置为日期时间,而是将日期时间值转换为数字并更改刻度标签。显式创建轴并设置正确的格式有效。
在此
import matplotlib.pyplot as plt
import pandas as pd
times = pd.date_range('2021-12-07', periods=500, freq='D')
yvalues = range(times.size)
df = pd.DataFrame(yvalues, times)
fig, ax = plt.subplots(1)
fig.autofmt_xdate()
ax.axvline(pd.to_datetime('2023-01-23'), color='r', linestyle='--', lw=2)
ax = df.plot(ax=ax, title='Random Forest Regressor Performance')
plt.show()
这导致 plot