Python 你如何在 Pandas 的时间序列图上绘制一条垂直线?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19213789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you plot a vertical line on a time series plot in Pandas?
提问by aetodd
How do you plot a vertical line (vlines) in a Pandas series plot? I am using Pandas to plot rolling means, etc and would like to mark important positions with a vertical line. Is it possible to use vlines or something similar to accomplish this? If so, could someone please provide an example? In this case, the x axis is date-time.
如何在 Pandas 系列图中绘制垂直线(vlines)?我正在使用 Pandas 绘制滚动方式等,并想用垂直线标记重要位置。是否可以使用 vlines 或类似的东西来实现这一点?如果是这样,有人可以提供一个例子吗?在这种情况下,x 轴是日期时间。
回答by tacaswell
回答by zbinsd
If you have a time-axis, and you have Pandas imported as pd, you can use:
如果您有时间轴,并且将 Pandas 导入为 pd,则可以使用:
ax.axvline(pd.to_datetime('2015-11-01'), color='r', linestyle='--', lw=2)
For multiple lines:
对于多行:
xposition = [pd.to_datetime('2010-01-01'), pd.to_datetime('2015-12-31')]
for xc in xposition:
ax.axvline(x=xc, color='k', linestyle='-')
回答by Roman Orac
DataFrame plot function returns AxesSubplot object and on it, you can add as many lines as you want. Take a look at the code sample below:
DataFrame plot 函数返回 AxesSubplot 对象,您可以在其上添加任意数量的行。看看下面的代码示例:
%matplotlib inline
import pandas as pd
df = pd.DataFrame(index=pd.date_range("2019-07-01", "2019-07-31"))
df["y"] = pd.np.logspace(0, 1, num=len(df))
ax = df.plot()
# you can add here as many lines as you want
ax.axhline(6, color="red", linestyle="--")
ax.axvline("2019-07-24", color="red", linestyle="--")