pandas 绘制时间序列,在选定日期有垂直线 [英] Pandas graphing a timeseries, with vertical lines at selected dates

查看:63
本文介绍了 pandas 绘制时间序列,在选定日期有垂直线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑此时间序列,即Wikipedia类别中的累计编辑数.

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

我要这样绘制图形:

In [567]:

cum_edits.plot()

Out[567]:

<matplotlib.axes.AxesSubplot at 0x1359c810>

我想在每次total_edits/n ; e.g. n=10编辑之后绘制垂直线.我很容易计算出这些.

I would like to plot also vertical lines, after every total_edits/n ; e.g. n=10 edits. I calculate these easily.

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)]

尽管我遇到两个问题,但是通常一个人可以使用axvline().即使我调用plt.axvline(x=0.5, color='r')只是为了生成任意行,我也看不到它在大熊猫图的顶部.顺便说一下,我正在将IPython与%pylab inline一起使用.其次,由于翻译对我而言是不可见的,因此我现在不将如何将日期转换为在cum_edits.plot()中使用的x位置.我应该去产生这些垂直线吗?

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 inline by 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?

推荐答案

感谢@TomAugspurger

Thanks to @TomAugspurger

解决方案是将轴放回原处,然后使用ax.vlines.

The solution is to get your axes back, and then use ax.vlines.

ax = cum_edits.plot()
ymin, ymax = ax.get_ylim()
ax.vlines(x=dates, ymin=ymin, ymax=ymax-1, color='r')

最后一个小问题是,如果vlines长于ymax,则matplotlib会在图的顶部添加额外的空间,因此我将长度略微减小为小于原始轴,这就是为什么看到ymax=ymax-1.

One last niggle is that if the vlines are ymax long, 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.

这篇关于 pandas 绘制时间序列,在选定日期有垂直线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆