【问题标题】:How to draw vertical average lines for overlapping histograms in a loop如何在循环中为重叠直方图绘制垂直平均线
【发布时间】:2021-01-16 01:58:12
【问题描述】:

我正在尝试使用 matplotlib 为使用循环的每个重叠直方图绘制两条平均垂直线。第一张画好了,第二张不知道怎么画。我正在使用数据集中的两个变量来绘制直方图。一个变量(feat)是分类变量(0 - 1),另一个变量(objective)是数值变量。代码如下:

for chas in df[feat].unique():
   plt.hist(df.loc[df[feat] == chas, objective], bins = 15, alpha = 0.5, density = True, label = chas)
   plt.axvline(df[objective].mean(), linestyle = 'dashed', linewidth = 2)
   plt.title(objective)
   plt.legend(loc = 'upper right')

我还必须在图例中添加每个直方图的均值和标准差值。

我该怎么做?提前谢谢你。

【问题讨论】:

    标签: python-3.x matplotlib histogram


    【解决方案1】:

    我建议你使用axes 来绘制你的图。请看下面的代码和艺术家教程here

    import numpy as np
    import matplotlib.pyplot as plt
    # Fixing random state for reproducibility
    np.random.seed(19680801)
    
    mu1, sigma1 = 100, 8
    mu2, sigma2 = 150, 15
    
    x1 = mu1 + sigma1 * np.random.randn(10000)
    x2 = mu2 + sigma2 * np.random.randn(10000)
    
    
    fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
    # the histogram of the data
    lbs = ['a', 'b']
    colors = ['r', 'g']
    for i, x in enumerate([x1, x2]):
        n, bins, patches = ax.hist(x, 50, density=True, facecolor=colors[i], alpha=0.75, label=lbs[i])
        ax.axvline(bins.mean())
    ax.legend()
    

    【讨论】:

    • 感谢@ted930511 的回复。但是我怎样才能从循环内部做到这一点?并将每个直方图的平均值和标准差值添加到图例中?
    • 您可以在hist 中使用label,如果它解决了您的问题,请接受它。查看更新的代码
    猜你喜欢
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 2015-01-22
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多