如何注释堆积条形图的每个部分?

时间:2020-09-12 00:48:00

标签: python pandas matplotlib

enter image description here

我一直在尝试用上面显示的值注释堆积的条形图的每个子量(值不准确,只是一个例子)。

df.iloc[1:].T.plot(kind='bar', stacked=True)
plt.show()

我使用的数据框: enter image description here

链接的帖子有点类似于我的问题,但是我不理解该答案中给出的代码,也没有给出任何解释。

Annotating Values in Stacked Bar Chart Matplotlib

1 个答案:

答案 0 :(得分:1)

  • Transpose数据框,然后将pandas.DataFrame.plot.barstacked=True一起使用。
  • 返回ndarray,每列带有subplots=True的{​​{3}}。
    • 在该图的情况下,ax.patches包含9个matplotlib.axes.Axes对象,每个条形图的每个分段都有一个。
      • 通过使用与此对象相关的方法,可以提取heightwidthxy的位置,并将其用于注释矩形。 / li>
  • 此问题与matplotlib.patches.Rectangle的不同之处在于,另一个问题需要提取并使用替代文本作为标签,并且此数据帧需要转置。
import pandas as pd
import matplotlib.pyplot as plt

data = {'var': ['TR', 'AC', 'F&B'], '2019 1Q': [6600, 1256, 588], '2019 2Q': [6566, 1309, 586], '2019 3Q': [7383, 1525, 673]}
df = pd.DataFrame(data)
df.set_index('var', inplace=True)

# display(df)
     2019 1Q  2019 2Q  2019 3Q
var                           
TR      6600     6566     7383
AC      1256     1309     1525
F&B      588      586      673

ax = df.T.plot.bar(stacked=True)
plt.legend(title='Categories', bbox_to_anchor=(1.05, 1), loc='upper left')

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)

How to annotate a stacked bar chart with word count and column name?