【问题标题】:How to add percentages on top of bars in seaborn FacetGrid?如何在 seaborn FacetGrid 的条形顶部添加百分比?
【发布时间】:2019-12-09 14:14:12
【问题描述】:

我希望在 catplot 中的条形顶部添加一个 % 值。我尝试使用此answer 中的以下代码。但我收到一条错误消息:

a=df.groupby([ var,Gender,strata]).agg({'one':'count'}).reset_index()
total = float(len(a))
sns.set_palette("Set2")
sns.set_style("whitegrid")
sns.despine()
g = sns.catplot(x="one", y=var,hue= Gender, col=strata,
                        data=a, kind="bar",
                        height=6, aspect=1);
# g.fig.suptitle(var) # if we want to add the title
g.set_axis_labels(x_var="")
for p in g.patches:
     height = p.get_height()
     ax.text(p.get_x()+p.get_width()/2.,
                height + 3,
                '{:1.2f}'.format(height/total),
                ha="center") 

错误信息如下

'FacetGrid' object has no attribute 'patches'

【问题讨论】:

标签: python plot seaborn


【解决方案1】:

sns.catplot 返回一个FacetGrid

请参考docu

您可以使用ax 属性从FacetGrid 获取坐标轴

请参考docu

所以你需要替换你的代码:从g.patchesg.ax.patches

【讨论】:

  • 好的,现在出现新错误:当有多个绘图时,您必须使用.axes 属性(一个数组)。
  • 我以为只有一个情节。在这种情况下,您需要使用 facet_axis(row_i, col_j) 它在文档的最后提到
  • 抱歉,我不知道如何在我的代码中实现它。
  • 试试g.axes[0][0].patches
【解决方案2】:

您可以使用以下建议的答案

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

来自this question,虽然这不是公认的答案,但它对我有用。

致谢作者。

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2019-08-19
    • 2015-11-22
    • 2019-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    相关资源
    最近更新 更多