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

osc*_*876 2 python datetime matplotlib pandas

如何在特定日期向此图表添加垂直线标记?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()
Run Code Online (Sandbox Code Playgroud)

输出图像

tdy*_*tdy 5

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

然后使用axvlinevlines

  • 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='--')
Run Code Online (Sandbox Code Playgroud)

输出