![](/img/trans.png)
[英]plot errorbar with matplotlib based on multiindex pandas dataframe
[英]Pandas: bar plot with multiIndex dataframe
我有一個帶有TIMESTAMP
列(不是索引)的pandas DataFrame,時間戳格式如下:
2015-03-31 22:56:45.510
我還有名為CLASS
和AXLES
列。 我想為AXLES
每個唯一值分別計算每個月的記錄數( AXLES
可以取3-12之間的整數值)。
我想出了resample
和groupby
的組合:
resamp = dfWIM.set_index('TIMESTAMP').groupby('AXLES').resample('M', how='count').CLASS
這似乎給了我一個multiIndex數據幀對象,如下所示。
In [72]: resamp
Out [72]:
AXLES TIMESTAMP
3 2014-07-31 5517
2014-08-31 31553
2014-09-30 42816
2014-10-31 49308
2014-11-30 44168
2014-12-31 45518
2015-01-31 54782
2015-02-28 52166
2015-03-31 47929
4 2014-07-31 3147
2014-08-31 24810
2014-09-30 39075
2014-10-31 46857
2014-11-30 42651
2014-12-31 48282
2015-01-31 42708
2015-02-28 43904
2015-03-31 50033
從這里,如何訪問此multiIndex對象的不同組件以創建以下條件的條形圖?
謝謝!
編輯 :以下代碼給我的情節,但我無法將xtick格式更改為MM-YY。
resamp[3].plot(kind='bar')
下面的編輯2是一個代碼片段,它生成一個類似於我的數據的小樣本:
dftest = {'TIMESTAMP':['2014-08-31','2014-09-30','2014-10-31'], 'AXLES':[3, 3, 3], 'CLASS':[5,6,7]}
dfTest = pd.DataFrame(dftest)
dfTest.TIMESTAMP = pd.to_datetime(pd.Series(dfTest.TIMESTAMP))
resamp = dfTest.set_index('TIMESTAMP').groupby('AXLES').resample('M', how='count').CLASS
resamp[3].plot(kind='bar')
編輯3:以下是解決方案:
A.繪制整個重采樣數據幀(基於@Ako的建議):
df = resamp.unstack(0)
df.index = [ts.strftime('%b 20%y') for ts in df.index]
df.plot(kind='bar', rot=0)
B.從重新采樣的數據幀中繪制單個索引(基於@Alexander的建議):
df = resamp[3]
df.index = [ts.strftime('%b 20%y') for ts in df.index]
df.plot(kind='bar', rot=0)
您可以生成和使用明確設置標簽ax.xaxis.set_major_formatter
用ticker.FixedFormatter
。 這將允許您使用時間戳值保留DataFrame的MultiIndex,同時以所需的%m-%Y
格式顯示時間戳:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.ticker as ticker
dftest = {'TIMESTAMP':['2014-08-31','2014-09-30','2014-10-31'], 'AXLES':[3, 3, 3], 'CLASS':[5,6,7]}
dfTest = pd.DataFrame(dftest)
dfTest.TIMESTAMP = pd.to_datetime(pd.Series(dfTest.TIMESTAMP))
resamp = dfTest.set_index('TIMESTAMP').groupby('AXLES').resample('M', how='count').CLASS
ax = resamp[3].plot(kind='bar')
ticklabels = [timestamp.strftime('%m-%Y') for axle, timestamp in resamp.index]
ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: ticklabels[int(x)]))
plt.gcf().autofmt_xdate()
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.