具有不同 histt​​ype 的堆叠直方图

Stacked histogram with different histtype

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

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

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)

此示例的问题是 'step' 直方图的边界比 'stepfilled' 直方图的宽度宽。有什么办法可以解决这个问题?

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

  • 直方图的 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()

这是 cross-hatching(plt.hist(..., hatch='X'))和黑边的样子: