grahama
grahama

Reputation: 321

How to Annotate Bars in a Seaborn Facetgrid (works in Factorplot)

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

Many thanks in advance

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

Upvotes: 2

Views: 4810

Answers (2)

igor.pereira.br
igor.pereira.br

Reputation: 71

You could use:

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

Upvotes: 7

grahama
grahama

Reputation: 321

This is the for loop code that will target the columns on each plot of a facetgrid

    for ax in g.axes.ravel():

Upvotes: 2

Related Questions