簡體   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