Pandas 绘制时间序列图,在选定日期带有垂直线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21488085/
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
Pandas graphing a timeseries, with vertical lines at selected dates
提问by notconfusing
Consider this timeseries, the cumulative number of edits in a Wikipedia category.
考虑这个时间序列,维基百科类别中的累积编辑次数。
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
I have am to graph this like so:
我必须像这样绘制图形:
In [567]:
cum_edits.plot()
Out[567]:
<matplotlib.axes.AxesSubplot at 0x1359c810>


I would like to plot also vertical lines, after every total_edits/n ; e.g. n=10edits. I calculate these easily.
每次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)]
Normally one can use axvline()although I encounter two problems. Even if I call plt.axvline(x=0.5, color='r')just to produce an arbitrary line, I do not see it on top of the pandas plot. I am using IPython with %pylab inlineby the way. And secondly, I do not now how to translate the dates into x position that are being used in cum_edits.plot()since the translation is invisible to me. Should I go about producing these vertical lines?
axvline()虽然我遇到了两个问题,但通常可以使用。即使我打电话plt.axvline(x=0.5, color='r')只是为了产生一条任意的线,我也没有在Pandas图的顶部看到它。%pylab inline顺便说一下,我正在使用 IPython 。其次,我现在不知道如何将日期翻译成正在使用的 x 位置,cum_edits.plot()因为翻译对我来说是不可见的。我应该去制作这些垂直线吗?
回答by notconfusing
Thanks to @TomAugspurger
感谢@TomAugspurger
The solution is to get your axes back, and then use ax.vlines.
解决方案是取回您的轴,然后使用ax.vlines.
ax = cum_edits.plot()
ymin, ymax = ax.get_ylim()
ax.vlines(x=dates, ymin=ymin, ymax=ymax-1, color='r')


One last niggle is that if the vlines are ymaxlong, then matplotlib adds extra space to the top of my plot, so I just slightly reduce the length to be less than the original axes, that is why you see the ymax=ymax-1.
最后一个小问题是,如果 vlines 很ymax长,那么 matplotlib 会在我的绘图顶部增加额外的空间,所以我只是将长度稍微减少到小于原始轴的长度,这就是为什么你看到ymax=ymax-1.

