2014-02-23 34 views
8

我的腦子疼餡大熊貓DataFrame.plot成matplotlib插曲

我有一個產生33個顯卡在一個長列中的某些代碼

#fig,axes = plt.subplots(nrows=11,ncols=3,figsize=(18,50)) 
accountList = list(set(training.account)) 
for i in range(1,len(accountList)): 
    training[training.account == accountList[i]].plot(kind='scatter',x='date_int',y='rate',title=accountList[i]) 
#axes[0].set_ylabel('Success Rate') 

我想每個這些地塊要進我上面已經提到過的數字,但是我所有的嘗試都失敗了。我試圖把ax=i放入劇情指令中,我得到了'numpy.ndarray' object has no attribute 'get_figure'。另外,當我縮小比例並在一個一個的數字中使用一個單獨的情節來做這件事時,我的x和y尺度都會發生變化。我覺得我接近答案,但我需要一點點推動。謝謝。

+0

我相信你需要使用類似ax = axes [i,j]的東西,但我可能是錯的。這有幫助嗎? http://pandas.pydata.org/pandas-docs/stable/visualization.html#targeting-different-subplots –

回答

13

軸線處理該subplots返回根據副區的請求的數目而變化:你得到一個單一手柄

  • 爲(1×1),
  • 爲(NX 1或1 xn)映射你得到一維(mxn)你得到一個2d數組的句柄。

看起來,你的問題來自界面從第二到第三種情況(即1d到2d軸陣列)的變化。如果您事先不知道陣列形狀將如何,以下片段可以提供幫助。

我發現numpy的的unravel_index有用的遍歷軸,如:

ncol = 3 # pick one dimension 
nrow = (len(accountList)+ ncol-1)/ncol # make sure enough subplots 
fig, ax = plt.subplots(nrows=nrow, ncols=ncol) # create the axes 

for i in xrange(len(accountList)): # go over a linear list of data 
    ix = np.unravel_index(i, ax.shape) # compute an appropriate index (1d or 2d) 

    accountList[i].plot(..., ax=ax[ix]) # pandas method plot 
    ax[ix].plot(...) # or direct axis object method plot (/scatter/bar/...) 

您也可以重塑返回數組所以,它是線性(正如我在this answer使用):

for a in ax.reshape(-1): 
    a.plot(...) 

正如在鏈接解決方案中指出的,如果您可能有1x1的子圖(然後接收單個軸手柄; axs = np.array(axs) 足夠)。


而且更仔細地(哎呀)讀取docs後,設置squeeze=False軍隊subplots返回NCOLS/NROWS的選擇的二維矩陣不管。 (squeeze默認爲True)。

如果你這樣做,你可以迭代兩個維度(如果它對你的數據來說很自然),或者使用上述任何一種方法來線性迭代你的數據並計算一個2d索引到ax

0

擴展在Bonlenfum的答案,這裏有一個方法與GROUPBY子句來做到這一點:

accountList = training.account.unique() 
accountList.sort() 
for i, group in training.groupby('account'): 
    ix = np.where(accountList==i)[0][0] 
    ix = np.unravel_index(ix, ax.shape) 
    group.plot(ax=ax[ix],title = i) 

這樣我們就可以用標題了圖表,並且還可以容納與值的組是缺少(即1 ,3,8)