如何在 Seaborn Facetgrid 中注释条形(适用于 Factorplot)

gra*_*ama 2 python matplotlib python-3.x seaborn

我试图将每个条形的值叠加到 4x4 Seaborn Facetgrid 的每个图中。下面的工作在因子图中。我如何修改它以使其在构面网格中工作?针对 g.axes.flat.patches 似乎也不起作用。

 # 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')
Run Code Online (Sandbox Code Playgroud)

提前谢谢了

(下面是facetgrid的缩写示例)

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')
Run Code Online (Sandbox Code Playgroud)

小智 7

你可以使用:

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')
Run Code Online (Sandbox Code Playgroud)