簡體   English   中英

使用循環創建多個圖並在一個中顯示單獨的 plot

[英]Create multiple plots using loop and show separate plot in one

我遇到了這個論壇的答案並有一個問題。 如何在一個 plot 中顯示單獨的 plot。 嘗試使用 plt.subplots(1, 4) 但不起作用。 以下是示例代碼:

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
for i in range(len(x)):
    plt.figure()
    plt.plot(x[i],y[i])
    

#plt.show()

您可以使用 plt.subplot() 如下:

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
plt.figure(figsize=[10,10])

for i in range(len(x)):
    plt.subplot(1,len(x)+1,i+1)
    plt.plot(x[i],y[i])
    plt.title('Plot: '+str(i+1))
plt.show()

這是 output 圖:

這是輸出圖

以下可以做到。 它使用zip遍歷列表(x 和 y 有 4 個嵌套列表)和子圖(在本例中為 2 x 2)。

x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]

fig = plt.figure(figsize=(10, 6))

for i,j in zip(list(range(0,4)), list(range(1,5)) ):
    ax = fig.add_subplot(2,2,j)
    ax.plot(x[i], y[i])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM