首页 > 解决方案 > Python pyplot.hist:如何将每个条形图的总和为 1?

问题描述

我目前的堆叠直方图编码如下:

x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]]
pyplot.hist(x_multi, 10, histtype='barstacked')

但是,我想将每个堆叠条缩放到 1 的高度,以便 y 轴现在描绘每个系列条表示的 bin 的百分比(即每个堆叠条的百分比)。像这样的东西:

在此处输入图像描述

但是,此图像来自网络上使用硬编码类别的不同示例(如 x 轴所示)。这可以使用 pyplot.hist 来完成,自动保留正确的分箱和 x 轴吗?

标签: pythonmatplotlib

解决方案


显然,没有一个简单的解决方案。最快的方法是使用 matplotlib 的hist函数计算直方图,然后对其进行归一化,然后使用 bar 命令重新绘制它。我现在将其推广到任意数量的堆叠单元。它还计算垃圾箱的真实中心,而不仅仅是边缘。

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
d = np.random.randn(300).reshape(3,100)

def percentage_bar_stack(data, bins=10):
    '''Creates a stacked histogram bar chart using data and a given amount of bins'''
    data_binned, edge_bins, patches = plt.hist(data.T, bins=bins, stacked=True, width=.5)
    plt.title('stacked bar chart, raw')

    real_bins = [(edge_bins[i]+edge_bins[i+1])/2 for i in range(bins)]

    data_binned = np.array(data_binned)
    data_binned /= data_binned.sum(0)

    plt.figure()
    print(data_binned)
    for i in range(len(data_binned)):
        plt.bar(real_bins, data_binned[i], bottom=data_binned[:i].sum(0), width=.5)
    plt.title('normalized to percentage')

percentage_bar_stack(d)

正确的堆积条形图标准化每条


推荐阅读