Plot multiple histograms as a grid

前端 未结 1 1142
清酒与你
清酒与你 2021-01-24 06:19

I am trying to plot multiple histograms on the same window using a list of tuples. I have managed to get it to sketch only 1 tuple at a time and I just can\'t seem to get it to

相关标签:
1条回答
  • 2021-01-24 07:15

    You need to define a grid of axes with plt.subplots taking into account the amount of tuples in the list, and how many you want per row. Then iterate over the returned axes, and plot the histograms in the corresponding axis. You could use Axes.hist, but I've always preferred to use ax.bar, from the result of np.unique, which also can return the counts of unique values:

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

    You can customise the above to whatever amount of rows/cols you prefer, for 3 rows for instance:

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

    0 讨论(0)
提交回复
热议问题