Python 带中心标签的堆叠条形图

Python 带中心标签的堆叠条形图,python,pandas,matplotlib,seaborn,bar-chart,Python,Pandas,Matplotlib,Seaborn,Bar Chart,我正试图“稳健地”将数据标签放在堆叠条形图的中心。下面给出了一个简单的代码示例和结果。如您所见,数据标签并不是在所有矩形中都居中。我错过了什么 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.

我正试图“稳健地”将数据标签放在堆叠条形图的中心。下面给出了一个简单的代码示例和结果。如您所见,数据标签并不是在所有矩形中都居中。我错过了什么

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()
为什么要写
va=“bottom”
?您必须使用
va=“center”

  • 下面的方法更简洁,更容易使用更多列进行缩放
  • 将数据放入pandas.DataFrame中是绘制堆叠条形图的最简单方法
  • 使用是绘制堆叠条形图的最简单方法。
    • 此方法返回其中一个
      matplotlib.axes.axes
      或一个
      numpy.ndarray
  • 由于
    seaborn
    只是
    matplotlib
    的高级API,因此这些解决方案也适用于
    seaborn
    绘图,如中所示
导入和测试数据帧
将熊猫作为pd导入
将matplotlib.pyplot作为plt导入
A=[45,17,47]
B=[91,70,72]
C=[68,43,13]
#熊猫数据帧
数据帧(数据={'A':A,'B':B,'C':C})
df.index=['C1','C2','C3']
A、B、C
C1 45 91 68
C2 17 70 43
C3 47 72 13
更新了matplotlib v3.4.2版的

  • 使用
    • 将自动使条形图中的值居中
  • 有关其他格式选项,请参见页面
  • 使用
    pandas v1.2.4
    进行测试,该版本使用
    matplotlib
    作为绘图引擎
  • 如果条形图的某些部分为零,请参见my,其中显示了如何为
    .bar\u label()
    自定义
    标签
ax=df.plot(kind='bar',stacked=True,figsize=(8,6),rot=0,xlabel='Class',ylabel='Count')
对于ax容器中的c:
ax.bar_标签(c,标签类型='center')

注释资源-来自
matplotlib v3.4.2
原始答案
  • 使用
    .patches
    方法解压缩对象列表,每个对象对应于堆叠条的每个部分。
    • 每个
      .Rectangle
      都有用于提取定义矩形的各种值的方法
    • 每个
      .Rectangle
      都是从左到右,从下到上的顺序,因此在遍历
      .patches
      时,每个级别的所有
      .Rectangle
      对象都是按顺序显示的
  • 标签是使用,
    label_text=f'{height}'
    制作的,因此可以根据需要添加任何其他文本,例如
    label_text=f'{height}%'
情节
plt.style.use('ggplot'))
ax=df.plot(stacked=True,kind='bar',figsize=(12,8),rot='horizontal')
#.补丁是图表中的所有内容
对于ax.patches中的rect:
#找到所有东西的位置
高度=矩形。获取高度()
width=rect.get_width()
x=rect.get_x()
y=rect.get_y()
#条形图的高度是数据值,可以用作标签
label_text=f'{height}'#f'{height:.2f}'以格式化十进制值
#ax.text(x,y,text)
标签x=x+宽度/2
标签y=y+高度/2
#仅当高度大于指定值时打印
如果高度>0:
ax.text(label_x,label_y,label_text,ha='center',va='center',fontsize=8)
ax.图例(bbox_to_anchor=(1.05,1),loc='左上角',borderaxespad=0。)
ax.set_ylabel(“计数”,fontsize=18)
ax.set_xlabel(“类”,fontsize=18)
plt.show()

  • 要绘制水平条,请执行以下操作:
    • kind='barh'
    • label\u text=f'{width}'
    • 如果宽度>0:
  • 归属:

hi:如何使值标签显示无小数?