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 ?
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)
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.