Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

python - How to share secondary y-axis between subplots in matplotlib

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 sharey in the call of subplot.

Below example shows my attempt, but it fails to share the secondary y-axis of both subplots. I'm using 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

The reason I used the axes() function to set the shared y-axis is that twinx doesn't accept the sharey keyword.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use Axes.get_shared_y_axes() like so:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...