matplotlib - 在 y 轴上绘制 3 个百分比直方图

matplotlib - Plot 3 histograms with percentage on y axis

我想在同一个图上绘制 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()

绘制上面代码的结果

您可以在 plt.hist 上通过 density=True:

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)

输出: