2010-06-14 137 views
2

我正在繪製matplotlib中由於某種原因不均勻居中的一對簡單的子圖。我繪製它們如下:在Python中matplotlib不均勻居中的subplots?

plt.figure() 
# first subplot 
s1 = plt.subplot(2, 1, 1) 
plt.bar([1, 2, 3], [4, 5, 6]) 
# second subplot 
s2 = plt.subplot(2, 1, 2) 
plt.pcolor(rand(5,5)) 

# add colorbar 
plt.colorbar() 

# square axes 
axes_square(s1) 
axes_square(s2) 

其中axes_square很簡單:

def axes_square(plot_handle): 
    plot_handle.axes.set_aspect(1/plot_handle.axes.get_data_ratio()) 

我得到的情節附後。頂部和底部的地塊不均勻居中。我希望他們的yaxis被對齊並且他們的盒子被對齊。

如果我刪除了plt.colorbar()調用,那麼這些圖將變爲居中。當pcolor的顏色條仍然顯示時,我怎樣才能使圖形居中?我想讓座標軸居中並使顏色條位於該對齊線之外,或者位於pcolor矩陣的左側或右側。

image of plots link

Image of uncentered subplots in matplotlib http://i45.tinypic.com/2i1kvtu.png

感謝。

回答

2

嗯,這可能不是你想要什麼,但它會工作:

from numpy.random import rand 
import matplotlib.pyplot as plt 

plt.figure() 
# first subplot 
s1 = plt.subplot(2, 2, 2) 
plt.bar([1, 2, 3], [4, 5, 6]) 
# second subplot 
s2 = plt.subplot(2, 2, 4) 
plt.pcolor(rand(5,5)) 

# square axes 
axes_square(s1) 
axes_square(s2) 

s_fake = plt.subplot(2, 2, 3) 
s_fake.set_axis_off() 
# add colorbar 
plt.colorbar() 

它只是使左側假對細胞,而不會顯示他們什麼。不漂亮,但它的作品。 ;)

而且,我猜那兩個進口在你的代碼隱...

+0

感謝。有沒有辦法做到這一點,而不會引入更多的子圖?我不確定爲什麼這個額外的副劇技巧會起作用?應該有一種方法來將它們置於中間,這聽起來像是「colorbar()」函數中的一個錯誤。 – user248237dfsf 2010-06-14 16:55:07

0

給一個cax參數彩條,指定其中你喜歡的顏色條:

plt.colorbar(cax=plt.gcf().add_axes((0.75,0.1,0.05,0.3))) 
+0

當我這樣做時,它會刪除pcolor矩陣上x和y標籤的手動設置,我也不確定如何設置add_axes。你如何確定正確的座標來傳遞它? 如果我把它放在水平方向而不是垂直方向,有沒有一種更簡單的方法讓顏色條不干擾圖的對齊? 謝謝。 – user248237dfsf 2010-06-14 17:45:23

+0

我看不到任何對刻度標籤的更改。你發佈了完整的代碼嗎? – 2010-06-14 17:55:31