【问题标题】:Pandas graphing a timeseries, with vertical lines at selected dates熊猫绘制时间序列,在选定日期有垂直线
【发布时间】:2014-02-24 14:54:01
【问题描述】:

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

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 编辑之后,我还想绘制垂直线。我很容易计算这些。

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') 只是为了产生一条任意线,我也没有在熊猫图的顶部看到它。顺便说一下,我正在使用带有%pylab inline 的 IPython。其次,我现在不知道如何将日期转换为 cum_edits.plot() 中使用的 x 位置,因为我看不到翻译。我应该开始制作这些垂直线吗?

【问题讨论】:

  • 试试plt.axvline(x=0.5, ymin=0, ymax=60000, color='r')。我认为它是绘图,但在你的大比例尺上太小了。此外,您可能希望从您的绘图中取回坐标轴ax = cum_edits.plot() 并使用ax.vline(dates, 0, 60000),因为ax.vline 可以采用xs 的向量,但我认为axvline 只能采用缩放器。
  • @TomAugspurger。太好了,当我使用ax = cum_edits.plot()ax.vlines(dates, ymin=0, ymax=60000) 时,它可以工作。 (顺便说一句,它是 vline__s__)。除了最后的接触,ymax 自动缩放到情节的顶部。如何从我回来的坐标轴ax 推断出好的ymax
  • ax.get_ylim() 给出一个带有(lower, upper) 边界的元组。获取这些并根据需要添加或减去更多。

标签: python matplotlib pandas


【解决方案1】:

感谢@TomAugspurger

解决方案是把你的轴拿回来,然后使用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.

【讨论】:

  • @Abramodj 这个答案没有解决这个问题的特殊需求!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-01
  • 2021-01-13
  • 2014-01-01
  • 1970-01-01
相关资源
最近更新 更多