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

时间:2020-06-01 15:30:31

标签: matplotlib plot histogram

我正在尝试在同一图上绘制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()

绘制以上代码的结果

Plot Result of code above !

1 个答案:

答案 0 :(得分:1)

您可以在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)

输出:

enter image description here