大熊猫绘制时间序列图,在选定日期显示垂直线

not*_*ing 18 python matplotlib pandas

考虑这个时间序列,维基百科类别中的累计编辑数.

In [555]:
cum_edits.head()
Out[555]:
2001-08-31 23:37:28    1
2001-09-01 05:09:28    2
2001-09-18 10:01:17    3
2001-10-27 06:52:45    4
2001-10-27 07:01:45    5
Name: edits, dtype: int64
In [565]:
cum_edits.tail()
Out[565]:
2014-01-29 16:05:15    53254
2014-01-29 16:07:09    53255
2014-01-29 16:11:43    53256
2014-01-29 18:09:44    53257
2014-01-29 18:12:09    53258
Name: edits, dtype: int64
Run Code Online (Sandbox Code Playgroud)

我要像这样绘制图形:

In [567]:

cum_edits.plot()

Out[567]:

<matplotlib.axes.AxesSubplot at 0x1359c810>
Run Code Online (Sandbox Code Playgroud)

累积编辑

我希望在每次total_edits/n ; e.g. n=10编辑后也绘制垂直线.我很容易计算出来.

In [568]:

dates

Out[568]:

[Timestamp('2006-06-04 04:46:22', tz=None),
 Timestamp('2007-01-28 23:53:02', tz=None),
 Timestamp('2007-09-16 10:52:02', tz=None),
 Timestamp('2008-04-28 21:20:40', tz=None),
 Timestamp('2009-04-12 22:07:13', tz=None),
 Timestamp('2010-04-09 18:45:37', tz=None),
 Timestamp('2011-03-28 23:38:12', tz=None),
 Timestamp('2012-05-24 13:44:35', tz=None),
 Timestamp('2013-03-05 17:57:29', tz=None),
 Timestamp('2014-01-29 16:05:15', tz=None)]
Run Code Online (Sandbox Code Playgroud)

通常axvline()我会遇到两个问题.即使我plt.axvline(x=0.5, color='r')只是打电话来产生任意一条线,我也不会在大熊猫的情节中看到它.我%pylab inline顺便使用IPython .其次,我现在不知道如何将日期转换为正在使用的x位置,cum_edits.plot()因为翻译对我来说是不可见的.我应该去制作这些垂直线吗?

not*_*ing 29

感谢@TomAugspurger

解决方案是让你的轴恢复,然后使用ax.vlines.

ax = cum_edits.plot()
ymin, ymax = ax.get_ylim()
ax.vlines(x=dates, ymin=ymin, ymax=ymax-1, color='r')
Run Code Online (Sandbox Code Playgroud)

与vlines的解决方案

最后一个问题是,如果vlines很ymax长,那么matplotlib会在我的绘图顶部添加额外的空间,所以我只是将长度略微缩小到小于原始轴,这就是你看到的原因ymax=ymax-1.