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.
MatPlotLib with Python To change the range of X and Y axes, we can use xlim() and ylim() methods.
Adjust axis limits: To set the limits of x and y axes, we use the commands plt. xlim() and plt. ylim().
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.
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)
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)
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())
You could use shared axes which will share the x- and/or y-limits, but allow to customise the axes in any other way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With