【问题标题】:Plot two histograms on single chart with matplotlib使用 matplotlib 在单个图表上绘制两个直方图
【发布时间】:2011-10-15 19:38:53
【问题描述】:

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

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

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

【问题讨论】:

    标签: python matplotlib plot histogram


    【解决方案1】:

    这里有一个工作示例:

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

    【讨论】:

    • 在绘图前设置pyplot.hold(True)不是一个好主意,以防万一吗?
    • 不确定是否在我的 matplotlib 配置参数中设置了 hold(True) 或 pyplot 默认行为是这样的,但对我来说,代码可以正常工作。该代码是从一个更大的应用程序中提取的,到目前为止没有任何问题。无论如何,我在编写代码时已经对自己提出了很好的问题
    • @joaquin:我如何指定 x 为蓝色而 y 为红色?
    • 当我重现情节时,条形的边缘颜色默认为None。如果您想要与图中所示相同的设计,您可以将两者中的edgecolor 参数设置为k(黑色)。图例的过程与此类似。
    • 更简单:pyplot.hist([x, y], bins, alpha=0.5, label=['x', 'y']).
    【解决方案2】:

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

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

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

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

    【讨论】:

    • @GustavoBezerra,如何使用plt.hist为每个直方图生成一个pdf文件?我使用pandas.read_csv 加载了我的数据,该文件有 36 列和 100 行。所以我想要 100 个 pdf 文件。
    • @Sigur 那完全离题了。请谷歌或提出一个新问题。这似乎是相关的:stackoverflow.com/questions/11328958/…
    • @stochastic_zeitgeist 我同意@pasbi。我将您的评论与熊猫数据框一起使用,因为由于 nans,我需要不同的权重。使用x=np.array(df.a)y=np.array(df.b.dropna()) 它基本上最终成为plt.hist([x, y], weights=[np.ones_like(x)/len(x), np.ones_like(y)/len(y)])
    • 如果您的样本量差异很大,您可能希望使用双轴进行绘图以更好地比较分布。见below
    • @AgapeGal'lo 请参考安德鲁的回答。
    【解决方案3】:

    如果您有不同的样本量,可能很难将分布与单个 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()
    

    在这种情况下,您可以在不同的轴上绘制两个数据集。为此,您可以使用 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()
    

    【讨论】:

    • 这是一个很好的简短答案,除了您还应该添加如何在每个刻度标签上居中条形
    【解决方案4】:

    作为对Gustavo Bezerra's answer的补充:

    如果您希望对每个直方图进行归一化normed for mpldensity for mpl>=3.1)您不能只使用 @987654328 @,您需要为每个值设置权重:

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

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

    【讨论】:

      【解决方案5】:

      您应该使用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)
      

      【讨论】:

        【解决方案6】:

        当数据大小不同时,这是在同一个图上绘制两个并排的直方图的简单方法:

        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】:

          【讨论】:

          • 不同之处在于,使用 hist 您可以绘制频率图。也许你应该展示如何去做。 pandas 的频率 + 条形图 = hist()
          【解决方案8】:

          也是一个与华金回答非常相似的选项:

          import random
          from matplotlib import pyplot
          
          #random data
          x = [random.gauss(3,1) for _ in range(400)]
          y = [random.gauss(4,2) for _ in range(400)]
          
          #plot both histograms(range from -10 to 10), bins set to 100
          pyplot.hist([x,y], bins= 100, range=[-10,10], alpha=0.5, label=['x', 'y'])
          #plot legend
          pyplot.legend(loc='upper right')
          #show it
          pyplot.show()
          

          给出以下输出:

          【讨论】:

            【解决方案9】:

            绘制两个重叠的直方图(或更多)可能会导致图相当混乱。我发现使用step histograms(又名空心直方图)可以大大提高可读性。唯一的缺点是在 matplotlib 中,阶跃直方图的默认图例格式不正确,因此可以像下面的示例一样对其进行编辑:

            import numpy as np                   # v 1.19.2
            import matplotlib.pyplot as plt      # v 3.3.2
            from matplotlib.lines import Line2D
            
            rng = np.random.default_rng(seed=123)
            
            # Create two normally distributed random variables of different sizes
            # and with different shapes
            data1 = rng.normal(loc=30, scale=10, size=500)
            data2 = rng.normal(loc=50, scale=10, size=1000)
            
            # Create figure with 'step' type of histogram to improve plot readability
            fig, ax = plt.subplots(figsize=(9,5))
            ax.hist([data1, data2], bins=15, histtype='step', linewidth=2,
                    alpha=0.7, label=['data1','data2'])
            
            # Edit legend to get lines as legend keys instead of the default polygons
            # and sort the legend entries in alphanumeric order
            handles, labels = ax.get_legend_handles_labels()
            leg_entries = {}
            for h, label in zip(handles, labels):
                leg_entries[label] = Line2D([0], [0], color=h.get_facecolor()[:-1],
                                            alpha=h.get_alpha(), lw=h.get_linewidth())
            labels_sorted, lines = zip(*sorted(leg_entries.items()))
            ax.legend(lines, labels_sorted, frameon=False)
            
            # Remove spines
            ax.spines['top'].set_visible(False)
            ax.spines['right'].set_visible(False)
            
            # Add annotations
            plt.ylabel('Frequency', labelpad=15)
            plt.title('Matplotlib step histogram', fontsize=14, pad=20)
            plt.show()
            

            如您所见,结果看起来很干净。这在重叠甚至超过两个直方图时特别有用。根据变量的分布方式,这最多可用于大约 5 个重叠分布。不仅如此,还需要使用另一种类型的情节,例如here 呈现的情节之一。

            【讨论】:

              【解决方案10】:

              以防万一您有 pandas (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()
              

              【讨论】:

              • 我相信如果要比较的直方图有不同的样本大小,使用 pandas 将不起作用。这通常也是使用归一化直方图的上下文。
              【解决方案11】:

              这个问题之前已经回答过,但想添加另一个快速/简单的解决方法,可能会帮助其他访问者解决这个问题。

              import seasborn as sns 
              sns.kdeplot(mydata1)
              sns.kdeplot(mydata2)
              

              here 是一些有用的示例,用于 kde 与直方图的比较。

              【讨论】:

                【解决方案12】:

                当您想从二维 numpy 数组中绘制直方图时,有一个警告。您需要交换 2 个轴。

                import numpy as np
                import matplotlib.pyplot as plt
                
                data = np.random.normal(size=(2, 300))
                # swapped_data.shape == (300, 2)
                swapped_data = np.swapaxes(x, axis1=0, axis2=1)
                plt.hist(swapped_data, bins=30, label=['x', 'y'])
                plt.legend()
                plt.show()
                

                【讨论】:

                  【解决方案13】:

                  受所罗门回答的启发,但要坚持与直方图相关的问题,一个干净的解决方案是:

                  sns.distplot(bar)
                  sns.distplot(foo)
                  plt.show()
                  

                  确保首先绘制较高的直方图,否则您需要设置 plt.ylim(0,0.45) 以便不切断较高的直方图。

                  【讨论】:

                  • 一个有用的补充!
                  猜你喜欢
                  • 2016-08-13
                  • 2023-02-07
                  • 2015-01-10
                  • 1970-01-01
                  • 2019-01-15
                  • 2018-03-08
                  • 2016-06-09
                  相关资源
                  最近更新 更多