[英]matplotlib hist: how to plot a stacked hist with y_axis equal to 100%
我认为这不是matplotlib的hist-plot的简单选择。
但是,您可以使用numpy的直方图函数计算变量x和y的直方图,然后计算二者之和的分数,并使用标准条形图绘制数据:
plt.figure()
x=np.random.randn(1000)
y=np.random.randn(1000)
hx = np.histogram(x, bins=np.arange(-5, 5, 1))
hy = np.histogram(y, bins=np.arange(-5, 5, 1))
s = hx[0] + hy[0]
plt.bar(hx[1][:-1], hx[0]/s, label='x')
plt.bar(hy[1][:-1], hy[0]/s, bottom=hx[0]/s, label='y')
plt.legend()
为了在y轴上使用百分比而不是分数,您只需将所有y值乘以100:
plt.bar(hx[1][:-1], hx[0]/s*100, label='x')
plt.bar(hy[1][:-1], hy[0]/s*100, bottom=hx[0]/s*100, label='y')
Matplotlib使我们可以访问显示的矩形,并且可以对其进行操作。 以下代码假定所有垃圾箱的大小均相同,因此我们仅需缩放高度即可。
x=np.random.randn(1000)
y=np.random.randn(1000)
h = plt.hist([x,y],bins=np.arange(-5,5,1),stacked=True,density=True)
p1, p2 = h[-1] # the rectangles for bottom and top bars
ax = plt.gca()
ax.set_ylim(0, 100)
ax.set_xticks(np.arange(-5, 5, 1))
# go through each pair (bottom, top) and change the positions and length.
for i, (h1, h2) in enumerate(zip(p1.patches, p2.patches)):
h1_h = h1.get_height()
h2_h = h2.get_height()
if h1_h == 0 or h2_h == 0:
continue
h = h1_h+h2_h
h1.set_y(0)
h1.set_height(h1_h/h * 100)
h2.set_y(h1_h/h * 100)
h2.set_height(h2_h/h * 100)
h1.set_edgecolor('white')
h2.set_edgecolor('white')
h1.set_linewidth(1)
h2.set_linewidth(1)
编辑后: 缩放至0-100 2后的堆叠直方图
希望这可以帮助。
问候,
普拉桑斯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.