【问题标题】:matplotlib hist: how to plot a stacked hist with y_axis equal to 100%matplotlib hist:如何绘制 y_axis 等于 100% 的堆叠历史
【发布时间】:2019-09-26 20:31:08
【问题描述】:
x=np.random.randn(1000)
y=np.random.randn(1000)
plt.hist([x,y],bins=np.arange(-5,5,1),stacked=True,normed=True)

很抱歉中国被stackoverflow的表单图片网站屏蔽了。不知道你能不能看到我的照片。既然代码都在了,就可以运行了。

我希望 y_axis 等于 100%,并且图表应该显示每个间隔中 x 和 y 的百分比。那是:

我是手动画的……

【问题讨论】:

  • 如果matplotlib太难,那么ggplot/seaborn之类的python包只要能解决这个问题就可以了。

标签: python matplotlib


【解决方案1】:

我不认为这是 matplotlib 的 hist-plot 的简单选项。

但是,您可以使用 numpy 的 histogram 函数计算变量 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')

【讨论】:

    【解决方案2】:

    Matplotlib 让我们可以访问它显示的矩形并且我们可以操作它们。以下代码假设所有 bin 的大小相同,因此我们只需要 缩放高度。

    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)
    
    

    Stacked histogram after scaling to 0-100

    修改后:Stacked histogram after scaling to 0-100 2

    希望这会有所帮助。

    问候,

    普拉桑特

    【讨论】:

    • 这是真的!!例如,为了使其更清晰,我们可以添加更粗的边框。将以下内容添加到循环中:h1.set_edgecolor('white') h2.set_edgecolor('white') h1.set_linewidth(1) h2.set_linewidth(1)。希望这可以帮助。抱歉格式化;在评论中输入 enter 只是提交提交。
    • 我已经编辑了答案以添加适当的刻度并显示条形之间的分隔。
    猜你喜欢
    • 2016-08-14
    • 2016-08-15
    • 2023-02-24
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 2014-03-12
    • 1970-01-01
    相关资源
    最近更新 更多