3

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.

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.