【问题标题】:Stacked histogram with different histtype具有不同 histt​​ype 的堆叠直方图
【发布时间】:2020-08-11 18:05:21
【问题描述】:

我想在堆叠直方图中绘制不同的数据集,但我希望顶部的数据具有步长类型。

我通过拆分数据来完成此操作,前两组在堆叠直方图中,所有数据集的总和在不同的步长直方图中。这是代码和情节

mu, sigma = 100, 10
x1 = list(mu + sigma*np.random.uniform(1,100,100))
x2 = list(mu + sigma*np.random.uniform(1,100,100))
x3 = list(mu + sigma*np.random.uniform(1,100,100))

plt.hist([x1, x2], bins=20, stacked=True, histtype='stepfilled', color=['green', 'red'], zorder=2)
plt.hist(x1+x2+x3, bins=20, histtype='step', ec='dodgerblue', ls='--', linewidth=3., zorder=1)

此示例的问题是“阶梯”直方图的边界比“阶梯填充”直方图的宽度宽。有什么办法解决这个问题?

【问题讨论】:

    标签: python python-3.x matplotlib histogram


    【解决方案1】:

    要使条重合,需要解决两个问题:

    • 直方图的 bin 边界应该完全相等。它们可以通过以N+1 等份除以从整体最小值到最大值的距离来计算。对 plt.hist 的两次调用都需要相同的 bin 边界。
    • 'step' 直方图的粗边使条形更宽。因此,另一个直方图需要相同宽度的边缘。 plt.hist 似乎不接受堆叠直方图不同部分的颜色列表,因此需要设置固定颜色。或者,可以在循环生成的条之后更改边缘颜色。
    from matplotlib import pyplot as plt
    import numpy as np
    
    mu, sigma = 100, 10
    x1 = mu + sigma * np.random.uniform(1, 100, 100)
    x2 = mu + sigma * np.random.uniform(1, 100, 100)
    x3 = mu + sigma * np.random.uniform(1, 100, 100)
    
    xmin = np.min([x1, x2, x3])
    xmax = np.max([x1, x2, x3])
    bins = np.linspace(xmin, xmax, 21)
    _, _, barlist = plt.hist([x1, x2], bins=bins, stacked=True, histtype='stepfilled',
                             color=['limegreen', 'crimson'], ec='black', linewidth=3, zorder=2)
    plt.hist(np.concatenate([x1, x2, x3]), bins=bins, histtype='step',
             ec='dodgerblue', ls='--', linewidth=3, zorder=1)
    for bars in barlist:
        for bar in bars:
            bar.set_edgecolor(bar.get_facecolor())
    plt.show()
    

    这是带有交叉影线 (plt.hist(..., hatch='X')) 和黑边的样子:

    【讨论】:

    • 谢谢,很好的回答。如果我想使用histtype='step 将所有三个数据集堆叠在 1 个堆叠直方图中并仅更改顶部线条样式,这也会有所帮助。我可以将bar.set_edgecolor() 更改为bar.set_linestyle(),以防它对其他人有用。
    猜你喜欢
    • 1970-01-01
    • 2014-04-09
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2015-11-28
    • 2016-12-19
    相关资源
    最近更新 更多