[英]How to set axes limits in each subplot
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()
. 使用
axs.flat
将您axs
(2,3)阵列轴的长度为6的轴的平面可迭代容易得多使用比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
. 如果仅使用
range
语句在轴上进行迭代,而从不使用索引i
,则仅在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]. 是的,您可以在AxesSubplot对象即get_axes()[i]上使用.set_xlim和.set_ylim。
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: 或者稍微更Python:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.