简体   繁体   English

在 seaborn python 的分组条形图中注释文本

[英]Annotate texts in grouped barplot in seaborn python

I have difficulties to annotate text to bars in the grouped barplots that i created with seaborn.我很难将文本注释到我使用 seaborn 创建的分组条形图中的条形图上。 I've done some researches in here and google but cannot find the fixes.我在这里和谷歌做了一些研究,但找不到修复程序。 Below are codes that I have some far.以下是我有一些远的代码。


risk_df = df.groupby(['Year', 'Risk'], as_index=False).size().rename(columns= 'size':'Risk_count'}).set_index('Year')

fig, ax = plt.subplots(figsize = (12, 8))

x = risk_df.index
y = risk_df['Risk_count']

ax = sns.barplot(x=x,
                 y=y,
                 hue=risk_df['Risk'],
                 data = risk_df)

for p in ax.patches:
   ax.annotate(format(p.get_height()),
              (p.get_x() + p.get_width() / 2),
               p.get_height(),
               ha='center', 
               va='center',
               xytext=(0, 9),
               textcoords='offset points')

plt.title('Reports by risk rating', size = 18)
plt.tight_layout()


The code above show me the error that "TypeError: init () got multiple values for argument 'xytext'"上面的代码向我显示了“TypeError: init () got multiple values for argument 'xytext'”的错误

The current plot is look like this, but I would like to add number of observations per category of risk per year.当前的 plot 看起来像这样,但我想添加每年每个风险类别的观察次数。 Thanks first for your helps!!首先感谢您的帮助!! 在此处输入图像描述

The coordinates of the annotations need to be set in tuples, so the parentheses are wrongly bound.注解的坐标需要在元组中设置,所以括号被错误绑定。

for p in ax.patches:
    ax.annotate(format(p.get_height()),
              (p.get_x() + p.get_width() / 2, p.get_height()),
               ha='center', 
               va='center',
               xytext=(0, 9),
               textcoords='offset points')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM