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

标签 python matplotlib

如果您有多个包含辅助 y 轴的子图(使用 twinx 创建),您如何在子图之间共享这些辅助 y 轴?我希望它们以自动方式平等缩放(因此不要在之后手动设置 y 限制)。 对于主 y 轴,这可以通过在 subplot 的调用中使用关键字 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')

这让我明白了:

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

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

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

最佳答案

您可以像这样使用 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()

在这里,我们只是将辅助轴连接在一起。

希望对您有所帮助。

关于python - 如何在 matplotlib 中的子图之间共享辅助 y 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12919230/

相关文章:

python - 导入错误 : No module named pyplot (even after installing matplotlib)

python - Ipywidgets 在交互式而不是小部件上观察方法

python - matplotlib安装ffmpeg需要了解什么

python - 如何在Python中改变Delaunay点的颜色?

python - 如何连接 3D 散点图上的点?

python - plt.show() 在spyder ide 中不起作用

python - 在python中覆盖列表的构造函数

python - 大型 python tornado 项目的最佳结构是什么?

python - gc.collect() 函数到底做了什么?

python - 使用 python matplotlib 用线绘制非连续数据