【问题标题】:matplotlib - Plot 3 histograms with percentage on y axismatplotlib - 在 y 轴上绘制 3 个带有百分比的直方图
【发布时间】:2020-06-01 15:30:31
【问题描述】:

我试图在同一个图上显示 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()

绘制上面代码的结果

【问题讨论】:

    标签: matplotlib plot histogram


    【解决方案1】:

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

    输出:

    【讨论】:

    • 效果很好,谢谢,但如果我更改 bin = [1,10, 2] 的 bin 规范,y 刻度标签似乎不匹配!怎么会?
    猜你喜欢
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 2020-10-17
    • 1970-01-01
    • 2013-07-26
    • 2013-12-22
    相关资源
    最近更新 更多