我想在堆叠的直方图中绘制不同的数据集,但我希望最上面的数据具有步长类型。
我通过拆分数据,堆叠的直方图中的前两个数据集和不同阶跃直方图中的所有数据集的总和来完成此操作。这是代码和情节
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)
此示例的问题是“阶梯”直方图的边界宽于“阶梯填充”直方图的宽度。有什么解决办法吗?
答案 0 :(得分:1)
要使条形重合,需要解决两个问题:
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')
)和黑色边缘的外观: