如何在 Seaborn Facetgrid 中注释条形(适用于 Factorplot) [英] How to Annotate Bars in a Seaborn Facetgrid (works in Factorplot)

查看:58
本文介绍了如何在 Seaborn Facetgrid 中注释条形(适用于 Factorplot)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将每个条形的值叠加到 4x4 Seaborn Facetgrid 的每个图中.下面的工作在Factorplot中.我如何修改它以使其在facetgrid中起作用?定位g.axes.flat.patches似乎也不起作用.

I'm trying to overlay a value to each bar into each plot of a 4x4 Seaborn Facetgrid. The below works in a Factorplot. How do I amend it to work in a facetgrid? Targeting g.axes.flat.patches doesn't seem to work either.

 # Annotate a value into each bar in each plot (Doesn't work)
 # Error: AttributeError: 'numpy.flatiter' object has no attribute 'patches'

    for p in g.axes.flat.patches:
        g.annotate("{:.1f}".format(p.get_height()) , 
                    (p.get_x() + p.get_width() / 2., p.get_height()-fudge), # Placement
                    ha='center', va='center', fontsize=12, color='white', rotation=0, xytext=(0, 20),
                    textcoords='offset points')

非常感谢

(下面的 facetgrid 的缩短示例)

(Shortened example for facetgrid below)

melt =df.ix[:, np.r_[14:15, 28:29, 167:171]]

# Melt 
melted =  pd.melt(melt, id_vars=['region','age'],
                  var_name='vote_method', 
                  value_name='popularity').dropna().sort_values(by="region")

g = sns.FacetGrid(melted, row="region", col="vote_method", hue="age",
                  palette=flatui, 
                  sharex=False, sharey=True,size=10, aspect=2)

# Have to pass interval in to get keep the X axis ordered
g.map(sns.barplot, 'age', 'pref', order=melted.age.unique())


g.set_titles(size=32, fontweight='light', fontname='Helvetica Neue', 
             alpha=1, color= '#404040')


# Adjust the arrangement of the plots in the facetgrid
g.fig.tight_layout(pad=5)

# Annotate a value into each bar in each plot
for p in g.axes.flat.patches:
    g.annotate("{:.1f}".format(p.get_height()) , 
                (p.get_x() + p.get_width() / 2., p.get_height()-fudge), # Placement
                ha='center', va='center', fontsize=12, color='white', rotation=0, xytext=(0, 20),
                textcoords='offset points')

推荐答案

您可以使用:

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')

这篇关于如何在 Seaborn Facetgrid 中注释条形(适用于 Factorplot)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆