2012-10-16 99 views
17

如果您有多個包含輔助y軸的子圖(使用twinx創建),如何在子圖之間共享這些輔助y軸?我希望它們能夠以自動的方式平均縮放(所以不需要手動設置y-限制)。 對於主y軸,這可以通過在子圖的呼叫中使用關鍵字sharedy來實現。如何在matplotlib中的子圖之間共享輔助y軸

下面的例子顯示了我的嘗試,但它未能共享兩個子圖的次要y軸。我使用Matplotlib/Pylab:

ax = [] 

#create upper subplot 
ax.append(subplot(211)) 
plot(rand(1) * rand(10),'r') 

#create plot on secondary y-axis of upper subplot 
ax.append(ax[0].twinx()) 
plot(10*rand(1) * rand(10),'b') 

#create lower subplot and share y-axis with primary y-axis of upper subplot 
ax.append(subplot(212, sharey = ax[0])) 
plot(3*rand(1) * rand(10),'g') 

#create plot on secondary y-axis of lower subplot 
ax.append(ax[2].twinx()) 
#set twinxed axes as the current axes again, 
#but now attempt to share the secondary y-axis 
axes(ax[3], sharey = ax[1]) 
plot(10*rand(1) * rand(10),'y') 

這讓我有點像:

Example of two subplots with failed sharing of secondary y-axis

我用軸的原因()函數設置共享Y軸是twinx不接受分享關鍵字。

我在Win7 x64上使用Python 3.2。 Matplotlib版本是1.2.0rc2。

回答

30

您可以使用Axes.get_shared_y_axes()像這樣:

from numpy.random import rand 
import matplotlib 
matplotlib.use('gtkagg') 
import matplotlib.pyplot as plt 

# create all axes we need 
ax0 = plt.subplot(211) 
ax1 = ax0.twinx() 
ax2 = plt.subplot(212) 
ax3 = ax2.twinx() 

# share the secondary axes 
ax1.get_shared_y_axes().join(ax1, ax3) 

ax0.plot(rand(1) * rand(10),'r') 
ax1.plot(10*rand(1) * rand(10),'b') 
ax2.plot(3*rand(1) * rand(10),'g') 
ax3.plot(10*rand(1) * rand(10),'y') 
plt.show() 

這裏,我們剛剛加盟副軸線在一起。

希望有所幫助。

+0

是的,這有助於我進一步,謝謝。我還加入了主要的y軸,以便他們也擁有共享的y軸。 – Puggie

+0

很高興我能幫到你。感謝上網點。 – dmcdougall

+1

它不起作用,第二個雙胞胎標度得到更新,但第二個雙胞胎情節保持不變。 – Mattia

相關問題