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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12919230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:10:30  来源:igfitidea点击:

How to share secondary y-axis between subplots in matplotlib

pythonmatplotlib

提问by Puggie

If you have multiple subplots containing a secondary y-axis (created using twinx), how can you share these secondary y-axis between the subplots? I want them to scale equally in an automatic way (so not setting the y-limits afterwards by hand). For the primary y-axis, this is possible by using the keyword shareyin the call of subplot.

如果您有多个包含次要 y 轴(使用twinx创建)的子图,您如何在子图之间共享这些次要 y 轴?我希望它们以自动方式平等地缩放(所以之后不要手动设置 y 限制)。对于主y轴,这是可能的,通过使用所述关键字sharey中的呼叫的插曲

Below example shows my attempt, but it fails to share the secondary y-axis of both subplots. I'm using Matplotlib/Pylab:

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

This gets me something like:

这让我得到了类似的东西:

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

次要 y 轴共享失败的两个子图示例

The reason I used the axes()function to set the shared y-axis is that twinxdoesn't accept the shareykeyword.

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

I'am using Python 3.2 on Win7 x64. Matplotlib version is 1.2.0rc2.

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

采纳答案by dmcdougall

You can use Axes.get_shared_y_axes()like so:

你可以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()

Here we're just joining the secondary axes together.

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

Hope that helps.

希望有帮助。