Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 369
meen Avatar asked Jul 04 '26 05:07

meen


1 Answers

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

like image 159
Mr. T Avatar answered Jul 06 '26 18:07

Mr. T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!