3

I created a subplot figure with this code:

f, axs =plt.subplots(2,3)

Now on a loop I make a plot on each subplot by doing:

for i in range(5):
 plt.gcf().get_axes()[i].plot(x,u)

Is there a similar code to set the axis limits of the subplot I'm accessing ?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
rsp
  • 339
  • 2
  • 3
  • 9

2 Answers2

4

Yes, there is, but let's clean up that code while we're at it:

f, axs = plt.subplots(2, 3)

for i in range(5): #are you sure you don't mean 2x3=6?
    axs.flat[i].plot(x, u)
    axs.flat[i].set_xlim(xmin, xmax)
    axs.flat[i].set_ylim(ymin, ymax) 

Using axs.flat transforms your axs (2,3) array of Axes into a flat iterable of Axes of length 6. Much easier to use than plt.gcf().get_axes().

If you only are using the range statement to iterate over the axes and never use the index i, just iterate over axs.

f, axs = plt.subplots(2, 3)

for ax in axs.flat: #this will iterate over all 6 axes
    ax.plot(x, u)
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax) 
wflynny
  • 18,065
  • 5
  • 46
  • 67
  • 2
    Don't think this works anymore, use ax.axes.set_xlim (xmin, xmax) etc – rhody Apr 21 '19 at 16:38
  • I can confirm that still still works with matplotlib 3. `plt.subplots` returns a `figure` and an array of `Axes` objects which all have the `set_{x,y}lim()` method. [Ref](https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes). – wflynny Apr 21 '19 at 23:21
1

Yes you can use the .set_xlim and .set_ylim on the AxesSubplot object that is get_axes()[i].

Example code in the style you gave:

import numpy as np
from matplotlib import pyplot as plt
f, axs =plt.subplots(2,3)
x = np.linspace(0,10)
u = np.sin(x)
for i in range(6):
    plt.gcf().get_axes()[i].plot(x,u)
    plt.gcf().get_axes()[i].set_xlim(0,5)
    plt.gcf().get_axes()[i].set_ylim(-2,1)

Or slightly more pythonically:

import numpy as np
from matplotlib import pyplot as plt
f, axs =plt.subplots(2,3)
x = np.linspace(0,10)
u = np.sin(x)
for sub_plot_axis in plt.gcf().get_axes():
    sub_plot_axis.plot(x,u)
    sub_plot_axis.set_xlim(0,5)
    sub_plot_axis.set_ylim(-2,1)
or1426
  • 929
  • 4
  • 7