【问题标题】:Plot multiple histograms as a grid将多个直方图绘制为网格
【发布时间】:2020-07-17 07:30:34
【问题描述】:

我正在尝试使用元组列表在同一窗口上绘制多个直方图。我设法让它一次只绘制 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()

从上面的代码可以看出,我可以一次绘制一个元组,比如 q1、q2 等,但是我如何概括它以便绘制所有这些元组。

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

感谢您的宝贵时间:)

【问题讨论】:

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


    【解决方案1】:

    您需要使用plt.subplots 定义一个轴网格,同时考虑到列表中元组的数量以及每行需要多少个。然后遍历返回的轴,并在相应的轴上绘制直方图。您可以使用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()
    

    【讨论】:

    • 我应该能够看到 10 个直方图。我在下面的行中看到 for i, (t, ax) in enumerate(zip(a, axes.flatten())): 元组不是我需要的元组,我需要 (1,0,1,2,3), ( 2,2,2,0,1) 等不是 (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)
    • 知道了,现在检查@alan
    • 谢谢@yatu。保持安全:)
    • 只是像这样的字母表中的字母? @艾伦
    • 很好,我想通了。我回去看看我从哪里得到我的元组并将值更改为 A、B 等。所以现在我的元组是字符串而不是整数。感谢您的帮助!
    猜你喜欢
    • 2015-06-14
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    相关资源
    最近更新 更多