繁体   English   中英

如何在每个子图中设置轴限制

[英]How to set axes limits in each subplot

我使用以下代码创建了子图图:

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

现在在循环上,通过执行以下操作在每个子图上绘制一个图:

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

是否有类似的代码来设置我正在访问的子图的轴限制?

是的,有,但是让我们在清理代码时对其进行清理:

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) 

使用axs.flat将您axs (2,3)阵列轴的长度为6的轴的平面可迭代容易得多使用比plt.gcf().get_axes()

如果仅使用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) 

是的,您可以在AxesSubplot对象即get_axes()[i]上使用.set_xlim和.set_ylim。

您所给样式的示例代码:

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)

或者稍微更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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM