将多个直方图绘制为网格

时间:2020-04-05 09:27:29

标签: python python-3.x matplotlib plot histogram

我正在尝试使用元组列表在同一窗口上绘制多个直方图。我设法使它一次只绘制一个元组,而我似乎无法使其与所有它们一起使用。

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()

从上面的代码中可以看到,我可以一次绘制一个元组,例如q1,q2等,但是我如何对其进行泛化以使其绘制所有元组。

我试图模仿这个python plot multiple histograms,这正是我想要的,但是我没有运气。

谢谢您的时间:)

1 个答案:

答案 0 :(得分:1)

您需要使用Mamaessen定义轴网格,其中要考虑列表中的元组数量以及每行要多少个元组。然后遍历返回的轴,并在相应的轴上绘制直方图。您可以使用plt.subplots,但是从np.unique的结果来看,我总是更喜欢使用Axes.hist,它也可以返回唯一值的计数:

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()

ax.bar

例如,您可以针对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()

enter image description here