熊猫中的时间序列绘图不一致

阿梅里奥·巴斯克斯·雷纳(Amelio Vazquez-Reina)

说我有一个数据帧df,其中df.index包含的datetime对象,例如

> df.index[0]
datetime.date(2014, 5, 5)

如果我绘制它,Pandas很好地保留了图中的datetime类型,这使用户可以更改时间序列采样以及图的格式设置选项:

  # Plot the dataframe:
  f     = plt.figure(figsize=(8,8))
  ax    = f.add_subplot(1,1,1)
  lines = df.plot(ax=ax)

  # Choose the sampling rate in terms of dates:
  ax.xaxis.set_major_locator(matplotlib.dates.WeekdayLocator(byweekday=(0,1,2,3,4,5,6),
                                                            interval=1))

  # We can also re-sample the X axis numerically if we want (e.g. every 4 steps):
  N = 4

  ticks      = ax.xaxis.get_ticklocs()
  ticklabels = [l.get_text() for l in ax.xaxis.get_ticklabels()]

  ax.xaxis.set_ticks(ticks[-1::-N][::-1])
  ax.xaxis.set_ticklabels(ticklabels[-1::-N][::-1])

  # Choose a date formatter using a date-friendly syntax:
  ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%b\n%d'))

  plt.show()

然而,上述不工作为boxplot(刻度标签x轴被渲染为空):

df2.boxplot(column='A', by='created_dt',ax=ax, sym="k.")

# same code as above ...

就像在上一个示例中一样,Pandas将x轴标签转换为字符串类型,因此格式化程序和定位符不再起作用。

这篇文章重用了以下线程的解决方案:

  1. 接受对熊猫时间序列图设置x轴主要和次要刻度线和标签的答案
  2. 接受的熊猫答案:条形图xtick频率

为什么?如何使用boxplot允许我使用matplotlib日期定位器和格式化程序的方式使用

CT Zhu

不,实际上,即使折线图也无法正常工作,如果显示年份,您将注意到问题:在下面的示例中,xticks而不是2000,而是1989。

In [49]:
df=pd.DataFrame({'Val': np.random.random(50)})
df.index=pd.date_range('2000-01-02', periods=50)
f     = plt.figure()
ax    = f.add_subplot(1,1,1)
lines = df.plot(ax=ax)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%y%b\n%d'))
print ax.get_xlim()
(10958.0, 11007.0)

在此处输入图片说明

In [50]:
matplotlib.dates.strpdate2num('%Y-%M-%d')('2000-01-02')
Out[50]:
730121.0006944444
In [51]:
matplotlib.dates.num2date(730121.0006944444)
Out[51]:
datetime.datetime(2000, 1, 2, 0, 1, tzinfo=<matplotlib.dates._UTC object at 0x051FA9F0>)

原来,datetime数据在不同的处理pandasmatplotlib:在后者,2000-1-2应该是730121.0006944444,而不是10958.0pandas

为了正确处理,我们需要避免使用pandasplot方法:

In [52]:
plt.plot_date(df.index.to_pydatetime(), df.Val, fmt='-')
ax=plt.gca()
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%y%b\n%d'))

在此处输入图片说明

同样适用于barplot

In [53]:
plt.bar(df.index.to_pydatetime(), df.Val, width=0.4)
ax=plt.gca()
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%y%b\n%d'))

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章