首页 > 解决方案 > matplotlib - 在 y 轴上绘制 3 个带有百分比的直方图

问题描述

我试图在同一个图上显示 3 个直方图,但与 y 轴上的百分比相对,但不确定如何。您可以看到我正在尝试做的事情,但我无法到达那里!酒吧不缩放财产,不知道如何做到这一点!请帮忙

data_1 = [1,1,2,3,4,4,5,6,7,7,7,8,9]
data_2 = [4,2,3,4,1,1,6,8,9,9,9,5,6]
data_3 = [1,2,3,4,5,6,7,8,9,9,4,3,7,1,2,3,2,5,7,3,4,7,3,8,2,3,4,7,2]

bin = [1,10,1]
bin[1] += bin[2]*2
bin[0] -= bin[2]
bins_list = np.arange(bin[0],bin[1],bin[2])
fig, ax = plt.subplots(figsize=(15, 10))

counts, bins, patches = plt.hist((np.clip(data_1 , bins_list[0], bins_list[-1]),np.clip(data_2, bins_list[0], bins_list[-1]),np.clip(data_3, bins_list[0], bins_list[-1])),
                        rwidth=0.8,
                        bins=bins_list, color=('blue', 'red', 'green'),
                        weights=None)

xlabels = bins[1:].astype(str)
xlabels[-1] = xlabels[-2] + '>'
xlabels[0] = xlabels[0] + '<'

for lb in range(1, len(xlabels)-1):
    xlabels[lb] = str(bins_list[lb])+'-'+xlabels[lb]

N_labels = len(xlabels)
plt.xticks(bin[2] * np.arange(N_labels)+bin[2]/2 + bin[0], rotation=300)
ax.set_xticklabels(xlabels)
total = 0

''' Add percentages and value for each bar '''
for c in range(len(patches)):
    for count, p in zip(counts[c], patches[c]):
        percentage = '%0.2f%%  ' % (100 * float(count) / counts[c].sum())
        total += 100 * float(count) / counts[c].sum()
        x1 = p.get_x()
        y1 = p.get_y() + p.get_height()
        ax.annotate(percentage, (x1, y1), rotation=270, fontsize = 10)

ax.yaxis.set_major_formatter(tkr.PercentFormatter(xmax=len(data_3)))


ax.grid(axis='y', color='r',  linestyle=':')
ax.set_title("Please help")

ax.set_axisbelow(True)
fig.tight_layout()

绘制上面代码的结果

绘制上面代码的结果!

标签: matplotlibplothistogram

解决方案


你可以density=True传递plt.hist

counts, bins, patches = plt.hist((np.clip(data_1 , bins_list[0], bins_list[-1]),
                                  np.clip(data_2, bins_list[0], bins_list[-1]),
                                  np.clip(data_3, bins_list[0], bins_list[-1])),
                        rwidth=0.8,
                        density=True,                                  # here
                        bins=bins_list, color=('blue', 'red', 'green'),
                        weights=None)

输出:

在此处输入图像描述


推荐阅读