Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the same axis limits for all subplots in matplotlib

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.

like image 713
MrArsGravis Avatar asked Jun 23 '15 15:06

MrArsGravis


People also ask

How do I change the axis range in Matplotlib?

MatPlotLib with Python To change the range of X and Y axes, we can use xlim() and ylim() methods.

What are the two ways to adjust axis limits of the plot using Matplotlib?

Adjust axis limits: To set the limits of x and y axes, we use the commands plt. xlim() and plt. ylim().

How do you limit the range of values on each of the axes Matplotlib?

Import matplotlib. To set x-axis scale to log, use xscale() function and pass log to it. To plot the graph, use plot() function. To set the limits of the x-axis, use xlim() function and pass max and min value to it. To set the limits of the y-axis, use ylim() function and pass top and bottom value to it.


4 Answers

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) 
like image 154
AZarketa Avatar answered Sep 18 '22 21:09

AZarketa


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) 
like image 41
xiaozhu123 Avatar answered Sep 18 '22 21:09

xiaozhu123


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())
like image 33
Jsowa Avatar answered Sep 19 '22 21:09

Jsowa


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

like image 27
Daniel Lenz Avatar answered Sep 18 '22 21:09

Daniel Lenz