簡體   English   中英

使用Matplotlib Python將單個圖繪制成一個圖

[英]Individual plots into one figure using matplotlib python

目標是生成具有多個子圖的單個圖形。 以下代碼生成4個單獨的圖

要繪制的子列表:可以在兩組數據上使用相同的循環嗎? x vs. y和b vs. p這兩個數據集之間的差異是x vs. y將繪制4個圖,而b vs. p將繪制2個圖

x = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y = [[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]

p = [[17, 16, 6, 15, 6, 7, 6, 7, 9, 11], [16, 13, 9, 11, 12, 13, 6, 12, 13, 7]]
b = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]]

colours=['r','g','b','k'] 

繪制它們的循環

for i in range(len(x)):
    plt.plot(x[i], y[i],colours[i])
    plt.show()

是否可以創建一個循環遍歷每個已創建圖並將其添加到一個圖形或單個pdf的函數,以便可以一次查看所有四個圖?

這是使用subplots解決問題的方法:

from matplotlib import 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],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
colours=['r','g','b','k']

fig, axes = plt.subplots(nrows=2, ncols=2)
i = 0 # moving index to plot different sublists of data 
for r in axes:
    for c in r:
        c.plot(x[i], y[i], color=colours[i], label='Sublist %d'%(i+1))
        i += 1
        c.legend()

plt.show()

@SpghttCd建議的替代方法

for i, ax in enumerate(axes.flatten()):
    ax.plot(x[i], y[i], color=colours[i], label='Sublist %d'%(i+1))
    ax.legend()

輸出量

在此處輸入圖片說明

數據集2 (如以下注釋中所提供:

x = [[17, 16, 6, 15, 6], [7, 6, 7, 9, 11], [16, 13, 9, 11, 12], [13, 6, 12, 13, 7]] 
y = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]

輸出(數據集2)

在此處輸入圖片說明

暫無
暫無

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

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