首页 文章

使用matplotlib同时绘制两个直方图

提问于
浏览
150

我使用文件中的数据创建了直方图,没有问题 . 现在我想在同一直方图中叠加来自另一个文件的数据,所以我做了类似的事情

n,bins,patchs = ax.hist(mydata1,100)
n,bins,patchs = ax.hist(mydata2,100)

但问题是,对于每个区间,只显示具有最高值的条,而另一个区间是隐藏的 . 我想知道如何用不同的颜色同时绘制两个直方图 .

8 回答

  • 3

    接受的答案给出了具有重叠条形的直方图的代码,但是如果您希望每个条形并排(就像我一样),请尝试以下变体:

    import numpy as np
    import matplotlib.pyplot as plt
    plt.style.use('seaborn-deep')
    
    x = np.random.normal(1, 2, 5000)
    y = np.random.normal(-1, 3, 2000)
    bins = np.linspace(-10, 10, 30)
    
    plt.hist([x, y], bins, label=['x', 'y'])
    plt.legend(loc='upper right')
    plt.show()
    

    enter image description here

    参考:http://matplotlib.org/examples/statistics/histogram_demo_multihist.html

    编辑[2018/03/16]:更新以允许绘制不同大小的数组,如@stochastic_zeitgeist所示

  • 0

    如果您的样本量不同,则可能难以将分布与单个y轴进行比较 . 例如:

    import numpy as np
    import matplotlib.pyplot as plt
    
    #makes the data
    y1 = np.random.normal(-2, 2, 1000)
    y2 = np.random.normal(2, 2, 5000)
    colors = ['b','g']
    
    #plots the histogram
    fig, ax1 = plt.subplots()
    ax1.hist([y1,y2],color=colors)
    ax1.set_xlim(-10,10)
    ax1.set_ylabel("Count")
    plt.tight_layout()
    plt.show()
    

    hist_single_ax

    在这种情况下,您可以在不同的轴上绘制两个数据集 . 为此,您可以使用matplotlib获取直方图数据,清除轴,然后在两个不同的轴上重新绘制它(移动bin边缘以使它们不重叠):

    #sets up the axis and gets histogram data
    fig, ax1 = plt.subplots()
    ax2 = ax1.twinx()
    ax1.hist([y1, y2], color=colors)
    n, bins, patches = ax1.hist([y1,y2])
    ax1.cla() #clear the axis
    
    #plots the histogram data
    width = (bins[1] - bins[0]) * 0.4
    bins_shifted = bins + width
    ax1.bar(bins[:-1], n[0], width, align='edge', color=colors[0])
    ax2.bar(bins_shifted[:-1], n[1], width, align='edge', color=colors[1])
    
    #finishes the plot
    ax1.set_ylabel("Count", color=colors[0])
    ax2.set_ylabel("Count", color=colors[1])
    ax1.tick_params('y', colors=colors[0])
    ax2.tick_params('y', colors=colors[1])
    plt.tight_layout()
    plt.show()
    

    hist_twin_ax

  • 97

    万一你有熊猫( import pandas as pd )或可以使用它:

    test = pd.DataFrame([[random.gauss(3,1) for _ in range(400)], 
                         [random.gauss(4,2) for _ in range(400)]])
    plt.hist(test.values.T)
    plt.show()
    
  • 302

    您应该使用 hist 返回的值中的 bins

    import numpy as np
    import matplotlib.pyplot as plt
    
    foo = np.random.normal(loc=1, size=100) # a normal distribution
    bar = np.random.normal(loc=-1, size=10000) # a normal distribution
    
    _, bins, _ = plt.hist(foo, bins=50, range=[-6, 6], normed=True)
    _ = plt.hist(bar, bins=bins, alpha=0.5, normed=True)
    

    Two matplotlib histograms with same binning

  • 2

    下面是一种简单的方法,当数据具有不同的大小时,在同一个图上绘制两个直方图并排其条形图:

    def plotHistogram(p, o):
        """
        p and o are iterables with the values you want to 
        plot the histogram of
        """
        plt.hist([p, o], color=['g','r'], alpha=0.8, bins=50)
        plt.show()
    
  • 7

    作为完成Gustavo Bezerra's answer

    如果你想 each histogram to be normalizednormed 表示mpl <= 2.1而 density 表示mpl> = 3.1)你不能只使用 normed/density=True ,你需要为每个值设置权重:

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.random.normal(1, 2, 5000)
    y = np.random.normal(-1, 3, 2000)
    x_w = np.empty(x.shape)
    x_w.fill(1/x.shape[0])
    y_w = np.empty(y.shape)
    y_w.fill(1/y.shape[0])
    bins = np.linspace(-10, 10, 30)
    
    plt.hist([x, y], bins, weights=[x_w, y_w], label=['x', 'y'])
    plt.legend(loc='upper right')
    plt.show()
    

    enter image description here

    作为比较,具有默认权重和 density=True 的完全相同的 xy 向量:

    enter image description here

  • 3
  • 15

    这里有一个有效的例子:

    import random
    import numpy
    from matplotlib import pyplot
    
    x = [random.gauss(3,1) for _ in range(400)]
    y = [random.gauss(4,2) for _ in range(400)]
    
    bins = numpy.linspace(-10, 10, 100)
    
    pyplot.hist(x, bins, alpha=0.5, label='x')
    pyplot.hist(y, bins, alpha=0.5, label='y')
    pyplot.legend(loc='upper right')
    pyplot.show()
    

    enter image description here

相关问题