如何在 matplotlib 中的特定日期绘制垂直线

How to plot vertical lines at specific dates in matplotlib

如何在特定日期向此图表添加垂直线标记? Week end 是日期栏。

fig, ax = plt.subplots(figsize=(20,9))
thirteen.plot.line(x='Week end', y='OFF', color='crimson', ax=ax)
thirteen.plot.line(x='Week end', y='ON', color='blue', ax=ax)
ax.set_ylim(bottom=0)
plt.show()

首先确保日期列 Week end 已转换 to_datetime

然后使用 axvline or vlines:

  • axvline一次只能绘制一条竖线,会自动填满整个y范围
  • vlines 可以一次绘制多条垂直线,但您必须指定 y 边界
# convert to datetime date type
thirteen['Week end'] = pd.to_datetime(thirteen['Week end'])

fig, ax = plt.subplots(figsize=(20, 9))
thirteen.plot.line(x='Week end', y='OFF', color='crimson', ax=ax)
thirteen.plot.line(x='Week end', y='ON', color='blue', ax=ax)

# plot vertical line at one date
ax.axvline(x='2013-07-01', color='k')

# plot vertical lines at two dates from y=0 to y=250
ax.vlines(x=['2013-11-01', '2014-04-15'], ymin=0, ymax=250, color='k', ls='--')