python条形堆积图_python – 带有中心标签的堆积条形图

我正试图在堆积条形图中“稳健地”将数据标签居中.下面给出一个简单的代码和结果.如您所见,数据标签并未真正居中于所有矩形.我错过了什么?

import numpy as np

import matplotlib.pyplot as plt

A = [45, 17, 47]

B = [91, 70, 72]

fig = plt.figure(facecolor="white")

ax = fig.add_subplot(1, 1, 1)

bar_width = 0.5

bar_l = np.arange(1, 4)

tick_pos = [i + (bar_width / 2) for i in bar_l]

ax1 = ax.bar(bar_l, A, width=bar_width, label="A", color="green")

ax2 = ax.bar(bar_l, B, bottom=A, width=bar_width, label="B", color="blue")

ax.set_ylabel("Count", fontsize=18)

ax.set_xlabel("Class", fontsize=18)

ax.legend(loc="best")

plt.xticks(tick_pos, ["C1", "C2", "C3"], fontsize=16)

plt.yticks(fontsize=16)

for r1, r2 in zip(ax1, ax2):

h1 = r1.get_height()

h2 = r2.get_height()

plt.text(r1.get_x() + r1.get_width() / 2., h1 / 2., "%d" % h1, ha="center", va="bottom", color="white", fontsize=16, fontweight="bold")

plt.text(r2.get_x() + r2.get_width() / 2., h1 + h2 / 2., "%d" % h2, ha="center", va="bottom", color="white", fontsize=16, fontweight="bold")

plt.show()

9cb60239da95cc2ce484066a69dcc6f8.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值