Setting the same axis limits for all subplots

97k views Asked by At

This problem seems simple enough, but I can't find a pythonic way to solve it. I have several (four) subplots that are supposed to have the same xlim and ylim. Iterating over all subplots à la

f, axarr = plt.subplots(4)
for x in range(n):
    axarr[x].set_xlim(xval1, xval2)
    axarr[x].set_ylim(yval1, yval2)

isn't the nicest way of doing things, especially for 2x2 subplots – which is what I'm actually dealing with. I'm looking for something like plt.all_set_xlim(xval1, xval2).

Note that I don't want anything else to change (ticks and labels should be controlled separately).

EDIT: I'm using the plt.subplots(2, 2) wrapper. Following dienzs answer, I tried plt.subplots(2, 2,sharex=True, sharey=True) – almost right, but now the ticks are gone except for the left and bottom row.

5

There are 5 answers

1
Daniel Lenz On

You could use shared axes which will share the x- and/or y-limits, but allow to customise the axes in any other way.

4
JSowa On

If you have multiple subplots, i.e.

fig, ax = plt.subplots(4, 2)

You can use it. It gets limits of y ax from first plot. If you want other subplot just change index of ax[0,0].

plt.setp(ax, ylim=ax[0,0].get_ylim())
0
BenS On

This is not at all elegant, but it worked for me...

fig, axes = plt.subplots(6, 3, sharex=True)
axes[0, 0].set_xlim(right=10000) # sharex=True propagates it to all plots
for i in range(6):
    for j in range(3):
        axes[i, j].plot('Seconds', df.columns[2+3*i+j], data=df)  # your plot instructions
plt.subplots_adjust(wspace=.5, hspace=0.2)
0
xiaozhu123 On

You can try this.

#set same x,y limits for all subplots
fig, ax = plt.subplots(2,3)
for (m,n), subplot in numpy.ndenumerate(ax):
    subplot.set_xlim(xval1,xval2)
    subplot.set_ylim(yval1,yval2)
1
AZarketa On

Set the xlim and ylim properties on the Artist object by matplotlib.pyplot.setp() https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.setp.html

# Importing matplotlib.pyplot package.
import matplotlib.pyplot as plt

# Assigning 'fig', 'ax' variables.
fig, ax = plt.subplots(2, 2)

# Defining custom 'xlim' and 'ylim' values.
custom_xlim = (0, 100)
custom_ylim = (-100, 100)

# Setting the values for all axes.
plt.setp(ax, xlim=custom_xlim, ylim=custom_ylim)