簡體   English   中英

時間序列繪制Pandas中的不一致性

[英]Time-series plotting inconsistencies in Pandas

假設我有一個數據幀df ,其中df.indexdatetime對象組成,例如

> 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. Pandas timeseries繪圖設置x軸主要和次要刻度和標簽的接受答案
  2. Pandas接受的答案:bar plot xtick frequency

為什么? 如何使用boxplot的方式,允許我使用matplotlib日期定位器和格式化?

不,實際上連線圖都沒有正常工作,如果你有年份出現,你會注意到問題:在下面的例子中,不是2000,xticks是在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'))

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM