2014-09-12 73 views
0

我想用條形圖顯示2D數據,我想要顯示每個X的總數以及每個X內的Y的比率。我的想法是嵌套的條形圖。於是,我開始與Y的比例的每個X中:在matplotlib中的每個子圖旁邊繪製條形圖嗎?

import pandas as pd 
import random 
import itertools as itoo 
import matplotlib.pyplot as plt 

random.seed(0) 
s=pd.Series([random.randint(1,10) for _ in range(100)], 
      index=pd.MultiIndex.from_tuples([(x,y) for x,y in itoo.product(range(10), repeat=2)], names=list("xy"))) 
fig, axes=plt.subplots(10, sharex=True) # no sharey since only ratios important 
for x, ax in zip(range(10), reversed(axes)): 
    sx=s[x] 
    ax.bar(sx.index, sx, align="center") 
    ax.set_xticks(range(10)) 
    ax.yaxis.set_ticks([]) 
    ax.set_ylabel(x) 
    tot=sx.sum() 
    #plot label `x` and a single hbar(width=tot) right next to plot?; 

http://i59.tinypic.com/3478xgx.png

我怎樣才能在每個柱圖的右側添加水平條的總額是多少?

基本上它會看起來像一個完整的hbar圖,在整個條形圖集合(它也應該有一個標記的x軸)右側的每個X的總計。將這些小節與相應的小節子圖對齊非常重要。我還想在子區塊和水平條之間按照「行」標籤。我也想讓給定的小區(因此吧)更窄。

+0

如果使用'subplot'不會爲你做它,也許你可以使用[ gridspec](http://matplotlib.org/1.3.1/users/gridspec.html)? – Evert 2014-09-12 11:51:37

+0

將總計條形圖與每一行完美對齊將會非常具有挑戰性? – Gerenuk 2014-09-12 12:36:43

+0

隨着gridspec它不會很難,沒有。 – Ajean 2014-09-12 19:22:48

回答

1

正如別人所說,使用gridspec可以爲你做。下面是如何做到這一點的例子:

import pandas as pd 
import random 
import itertools as itoo 
import matplotlib.pyplot as plt 
import matplotlib.gridspec as gridspec 
from numpy import arange,array 

random.seed(0) 
s=pd.Series([random.randint(1,10) for _ in range(100)], 
      index=pd.MultiIndex.from_tuples([(x,y) for x,y in itoo.product(range(10), repeat=2)], names=list("xy"))) 

fig=plt.figure() 
fig.subplots_adjust(hspace=0,wspace=0.5) 
gs=gridspec.GridSpec(10,8) 

axes=[fig.add_subplot(gs[0,:6])] 
[axes.append(fig.add_subplot(gs[i,:6],sharex=axes[0])) for i in range(1,10)] 

tot=[] # Keep track of totals 

for x, ax in zip(range(10), reversed(axes)): 
    sx=s[x] 
    ax.bar(sx.index, sx, align="center") 
    ax.set_xticks(range(10)) 
    ax.yaxis.set_ticks([]) 
    ax.set_ylabel(x) 
    tot.append(sx.sum()) 

#plot label `x` and a single hbar(width=tot) right next to plot 
axh=fig.add_subplot(gs[:,6:]) 
axh.barh(arange(10)-0.4,array(tot)) 
axh.set_yticks(range(10)) 
axh.set_ylim(-0.5,9.5) 
fig.savefig('test.pdf') 

而這裏的輸出是什麼樣子:

using gridspec

+0

我擔心這種方法不會很乾淨,因爲如果我有更多的行,它們可能不再對齊?但我想我必須忍受這一點,否則會變得非常複雜? – Gerenuk 2014-09-13 13:36:51

+0

我想通過刪除垂直條形圖(hspace = 0)之間的空間,就像我上面所做的那樣有助於對齊,但YMMV – tom 2014-09-14 12:18:53

相關問題