【问题标题】:How to create multiple histograms on separate graphs with matplotlib?如何使用 matplotlib 在单独的图形上创建多个直方图?
【发布时间】:2014-10-15 07:56:50
【问题描述】:

我有 5 个数据集,我想从中创建 5 个单独的直方图。目前他们都在一个图表上。如何更改它以生成两个单独的图表?

为简单起见,在下面的示例中,我只显示了两个直方图。我正在查看角度 a 在 3 个不同时间的分布,角度 b 的分布相同。

n, bins, patches = plt.hist(a)
plt.xlabel('Angle a (degrees)') 
plt.ylabel('Frequency')
n, bins, patches = plt.hist(b)
label='2pm,3pm,4pm'
loc = 'center'
plt.legend(label, loc)

plt.xlabel('Angle b(degrees)')        
plt.title('Histogram of b')
plt.ylabel('Frequency')
label='2pm,3pm,4pm'
loc = 'center'
plt.legend(label, loc)

plt.show()

【问题讨论】:

    标签: python matplotlib histogram enthought canopy


    【解决方案1】:

    这可能是你想使用 matplotlib 的object-oriented interface 的时候。有几种方法可以解决这个问题。

    首先,您可能希望每个图都在一个完全独立的图形上。在这种情况下,matplotlib 可以让您跟踪各种数字。

    import numpy as np
    import matplotlib.pyplot as plt
    
    a = np.random.normal(size=200)
    b = np.random.normal(size=200)
    
    fig1 = plt.figure()
    ax1 = fig1.add_subplot(1, 1, 1)
    n, bins, patches = ax1.hist(a)
    ax1.set_xlabel('Angle a (degrees)')
    ax1.set_ylabel('Frequency')
    
    fig2 = plt.figure()
    ax2 = fig2.add_subplot(1, 1, 1)
    n, bins, patches = ax2.hist(b)
    ax2.set_xlabel('Angle b (degrees)')
    ax2.set_ylabel('Frequency')
    

    或者,您可以将图形划分为多个子图,并在每个子图上绘制直方图。在这种情况下,matplotlib 可以让您跟踪各种子图。

    fig = plt.figure()
    ax1 = fig.add_subplot(2, 1, 1)
    ax2 = fig.add_subplot(2, 1, 2)
    
    n, bins, patches = ax1.hist(a)
    ax1.set_xlabel('Angle a (degrees)')
    ax1.set_ylabel('Frequency')
    
    n, bins, patches = ax2.hist(b)
    ax2.set_xlabel('Angle b (degrees)')
    ax2.set_ylabel('Frequency')
    

    回答this question解释add_subplot中的数字。

    【讨论】:

      【解决方案2】:

      我最近使用pandas 来做同样的事情。如果您是从 csv/text 读取,那么它可能真的很容易。

      import pandas as pd
      data = pd.read_csv("yourfile.csv") # columns a,b,c,etc
      data.hist(bins=20)
      

      它实际上只是将 matplotlib 包装到一个调用中,但效果很好。

      【讨论】:

      • 这也是我使用它的方式,但这也是我在这里的原因。从你开始使用data.a.hist()data.b.hist() 开始,它们都进入一个单独的图表,而我希望它们出现在单独的图表中。因此,接受的答案确实在这里有所帮助,而不幸的是,这个答案没有:)
      猜你喜欢
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 2011-10-15
      相关资源
      最近更新 更多