Pandas绘制时间序列图,并在选定日期处添加垂直线

22

考虑这个时间序列,即维基百科类别中编辑次数的累积。

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 ; 比如 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)]

通常可以使用axvline(),但我遇到了两个问题。 即使我调用plt.axvline(x = 0.5, color ='r')来绘制任意一条线,我也看不到它在pandas图的顶部。 我顺便说一下,我正在使用带有%pylab inline的IPython。 另外,我不知道如何将日期转换为在cum_edits.plot()中使用的x位置,因为这种转换对我来说是看不见的。 我该如何继续制作这些垂直线?


2
尝试使用 plt.axvline(x=0.5, ymin=0, ymax=60000, color='r')。我认为它正在绘制,但在您的大比例尺上太小了。此外,您可能希望从绘图中获取轴 ax = cum_edits.plot() 并使用 ax.vline(dates, 0, 60000),因为 ax.vline 可以接受一个 x 向量,但我认为 axvline 只能接受一个标量。 - TomAugspurger
1
@TomAugspurger。太棒了,当我使用 ax = cum_edits.plot() 并使用 ax.vlines(dates, ymin=0, ymax=60000) 时它有效。(顺便说一下,是 vline__s__)。除了最后的触摸是使 ymax 自动缩放到图的顶部以外,如何从返回的轴 ax 推断出一个好的 ymax 呢? - notconfusing
1
ax.get_ylim() 返回一个包含 (lower, upper) 边界的元组。根据需要获取它们并添加或减去更多。 - TomAugspurger
1个回答

35

感谢 @TomAugspurger

解决方案是获取您的轴,然后使用 ax.vlines

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

具有垂直线的解决方案

最后一个小问题是,如果这些垂直线的长度为ymax,那么matplotlib会在我的图形顶部添加额外的空间,因此我只需稍微减少长度使其小于原始坐标轴,这就是为什么你会看到ymax=ymax-1


1
@Abramodj 那个回答并没有解决这个问题的特定需求! - cd98

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接