簡體   English   中英

Plot 多個直方圖作為網格

[英]Plot multiple histograms as a grid

我正在嘗試使用元組列表在同一個 window 上 plot 多個直方圖。 我設法讓它一次只繪制 1 個元組,但我似乎無法讓它與所有這些元組一起工作。

import numpy as np
import matplotlib.pyplot as plt

a = [(1, 2, 0, 0, 0, 3, 3, 1, 2, 2), (0, 2, 3, 3, 0, 1, 1, 1, 2, 2), (1, 2, 0, 3, 0, 1, 2, 1, 2, 2),(2, 0, 0, 3, 3, 1, 2, 1, 2, 2),(3,1,2,3,0,0,1,2,3,1)] #my list of tuples

q1,q2,q3,q4,q5,q6,q7,q8,q9,q10 = zip(*a) #split into [(1,0,1,2,3) ,(2,2,2,0,1),..etc] where q1=(1,0,1,2,3)

labels, counts = np.unique(q1,return_counts=True) #labels = 0,1,2,3 and counts the occurence of 0,1,2,3

ticks = range(len(counts))
plt.bar(ticks,counts, align='center')
plt.xticks(ticks, labels)
plt.show()

正如您從上面的代碼中看到的那樣,我可以一次使用 plot 一個元組說 q1、q2 等,但是我如何對其進行概括以便繪制所有這些元組。

我試圖模仿這個python plot 多個直方圖,這正是我想要的,但是我沒有運氣。

感謝您的時間:)

您需要使用plt.subplots定義一個軸網格,同時考慮到列表中的元組數量以及每行需要多少個。 然后遍歷返回的軸,plot 對應軸的直方圖。 您可以使用Axes.hist ,但我一直更喜歡使用ax.bar的結果np.unique ,它也可以返回唯一值的計數:

from matplotlib import pyplot as plt
import numpy as np

l = list(zip(*a))
n_cols = 2
fig, axes = plt.subplots(nrows=int(np.ceil(len(l)/n_cols)), 
                         ncols=n_cols, 
                         figsize=(15,15))

for i, (t, ax) in enumerate(zip(l, axes.flatten())):
    labels, counts = np.unique(t, return_counts=True)
    ax.bar(labels, counts, align='center', color='blue', alpha=.3)
    ax.title.set_text(f'Tuple {i}')

plt.tight_layout()  
plt.show()

在此處輸入圖像描述

您可以將上述內容自定義為您喜歡的任意數量的行/列,例如3行:

l = list(zip(*a))
n_cols = 3
fig, axes = plt.subplots(nrows=int(np.ceil(len(l)/n_cols)), 
                         ncols=n_cols, 
                         figsize=(15,15))

for i, (t, ax) in enumerate(zip(l, axes.flatten())):
    labels, counts = np.unique(t, return_counts=True)
    ax.bar(labels, counts, align='center', color='blue', alpha=.3)
    ax.title.set_text(f'Tuple {i}')

plt.tight_layout()  
plt.show()

在此處輸入圖像描述

暫無
暫無

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

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