如何在Seaborn Facetgrid中注释条形图(在Factorplot中工作)

时间:2016-12-13 18:11:06

标签: python-3.x matplotlib seaborn

我正在尝试将每个条形图的值叠加到4x4 Seaborn Facetgrid的每个图中。以下工作在Factorplot中。如何修改它以在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')

非常感谢提前

(下面的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')

2 个答案:

答案 0 :(得分: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')

答案 1 :(得分:0)

这是for循环代码,它将定位facetgrid的每个图上的列

    for ax in g.axes.ravel():