如何在matplotlib中的子图之间共享辅助y轴

Pug*_*gie 31 python matplotlib

如果您有多个包含辅助y轴的子图(使用twinx创建),那么如何在子图之间共享这些辅助y轴?我希望它们能够以自动方式均等地扩展(因此不能手动设置y限制).对于主y轴,可以通过在子图调用中使用关键字sharey来实现.

下面的示例显示了我的尝试,但它无法共享两个子图的辅助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')
Run Code Online (Sandbox Code Playgroud)

这让我有点像:

辅助y轴共享失败的两个子图的示例

我使用axes()函数设置共享y轴的原因是twinx不接受sharey关键字.

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

小智 42

您可以这样使用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()
Run Code Online (Sandbox Code Playgroud)

在这里,我们只是将次轴连接在一起.

希望有所帮助.

  • 它不起作用,第二个孪生比例得到更新,但第二个孪生比例保持不变。 (2认同)
  • @mattia 可能遇到的问题:如果你在 `Axes.get_shared_y_axes().join()` 之前调用类似 `ax1.set_ylim()` 的函数,那么这两个轴将不会具有相同的比例(直到你以交互方式移动轴)。首先调用`get_shared_y_axes().join()`。顺便说一句,如果您在调用 `plot()` 等之后调用它,它可以正常工作。 (2认同)