【问题标题】:How to set axes limits in each subplot如何在每个子图中设置轴限制
【发布时间】:2015-07-27 11:16:23
【问题描述】:

我用这段代码创建了一个子图:

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

现在在一个循环中,我通过以下方式在每个子图上绘制一个图:

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

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

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    是的,有,但是让我们在处理该代码时清理一下:

    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) 
    

    【讨论】:

    • 不要再认为这行得通了,使用 ax.axes.set_xlim (xmin, xmax) 等
    • 我可以确认它仍然适用于 matplotlib 3。plt.subplots 返回一个 figure 和一个 Axes 对象数组,它们都具有 set_{x,y}lim() 方法。 Ref.
    【解决方案2】:

    是的,您可以在 get_axes()[i] 的 AxesSubplot 对象上使用 .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)
    

    或者稍微更蟒蛇:

    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)
    

    【讨论】:

      猜你喜欢
      • 2015-07-31
      • 2011-04-06
      相关资源
      最近更新 更多