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
459 views
in Technique[技术] by (71.8m points)

python - Setting the same scale for subplots but different limits using matplotlib

I want the scaling to be the same for my two subplots to make them comparable, but the limits should be set automatically. Here a small working example:

import matplotlib.pyplot as plt
import numpy as np

time = range(20)
y1 = np.random.rand(20)*2
y2 = np.random.rand(20) + 10

fig, axes = plt.subplots(2, figsize=(10,4), sharex=True, sharey=True)
# OPTION 2: fig, axes = plt.subplots(2, figsize=(10,4))
axes[0].plot(time, y1)
axes[1].plot(time, y2)

plt.show()

The plot looks like this:

enter image description here

and with option 2 uncommented it looks like this:

enter image description here

In the second plot, it looks like y1 and y2 are equally noisy which is wrong, but in plot 1 the axis limits are too high/low.

question from:https://stackoverflow.com/questions/66061570/setting-the-same-scale-for-subplots-but-different-limits-using-matplotlib

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

1 Reply

0 votes
by (71.8m points)

I am not aware of an automatic scaling function that does this (that does not mean it does not exist - actually, I would be surprised it did not exist). But it is not difficult to write it:

import matplotlib.pyplot as plt

#data generation
import numpy as np
np.random.seed(123)
time = range(20)
y1 = np.random.rand(20)*2
y2 = np.random.rand(20) + 10
y3 = np.random.rand(20)*6-12

#plot data
fig, axes = plt.subplots(3, figsize=(10,8), sharex=True)
for ax, y in zip(axes, [y1, y2, y3]):
    ax.plot(time, y)

#determine axes and their limits 
ax_selec = [(ax, ax.get_ylim()) for ax in axes]

#find maximum y-limit spread
max_delta = max([lmax-lmin for _, (lmin, lmax) in ax_selec])

#expand limits of all subplots according to maximum spread
for ax, (lmin, lmax) in ax_selec:
    ax.set_ylim(lmin-(max_delta-(lmax-lmin))/2, lmax+(max_delta-(lmax-lmin))/2)

plt.show()

Sample output:

enter image description here


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

1.4m articles

1.4m replys

5 comments

57.0k users

...