如何在 Seaborn Facetgrid 中为条形图添加计数标签?

How to add count labels to barplots in Seaborn Facetgrid?

我有一个 table 如下:

data = {'Platform':['Server A', 'Server A', 'Server A', 'Server A', 'Server A', 'Server A', 'Server B', 'Server B', 'Server B', 'Server B', 'Server B', 'Server B', 'Server C', 'Server C', 'Server C', 'Server C', 'Server C', 'Server C', 'Server C', 'Server C', 'Server C', 'Server D', 'Server D', 'Server D', 'Server D', 'Server D', 'Server D', 'Server D', 'Server D', 'Server D'],
    'Grade':['Excellent', 'Average', 'Excellent', 'Average', 'Excellent', 'Average','Excellent', 'Average', 'Excellent', 'Average', 'Excellent', 'Average', 'Excellent', 'Excellent', 'Excellent', 'Average', 'Average', 'Average', 'Bad', 'Bad', 'Bad', 'Excellent', 'Excellent', 'Excellent', 'Average', 'Average', 'Average', 'Bad', 'Bad', 'Bad'],
    'Colour':['Yellow', 'Yellow', 'Green', 'Green', 'Black', 'Black', 'Yellow', 'Yellow', 'Green', 'Green', 'Black', 'Black', 'Yellow', 'Green', 'Black', 'Yellow', 'Green', 'Black', 'Yellow', 'Green', 'Black', 'Yellow', 'Green', 'Black', 'Yellow', 'Green', 'Black', 'Yellow', 'Green', 'Black'], 
    'Count':[4115314,3879421,4240053,4019764,5398596,5019698,4652935,4140395,4786148,4306763,5691699,5181920,4046690,4202843,5320250,3772534,3945649,4936451,4242814,4490521,5341960,4926092,5095662,5816803,4404762,4587462,5298671,4948988,5146153,5720155]
       }

df = pd.DataFrame(data, columns = ['Platform', 'Grade', 'Colour', 'Count'])

我希望创建一个 FacetGrid,其中包含每个平台、等级和颜色的计数条形图。

g = sns.FacetGrid(df, col="Platform")
g.map_dataframe(sns.barplot, x="Grade", y="Counts", hue="Colour")
g.set_axis_labels("Grade", "Counts")
g.add_legend()
g.set_titles(col_template="{col_name}", row_template="{row_name}")

我可以使用此代码获得 FacetGrid。但是,如何在每个条的顶部添加计数标签?

我会使用传递给 g.map() 的自定义函数:

def annotate_bars(ax=None, fmt='.2f', **kwargs):
    ax = plt.gca() if ax is None else ax
    for p in ax.patches:
         ax.annotate('{{:{:s}}}'.format(fmt).format(p.get_height()), (p.get_x() + p.get_width() / 2., p.get_height()),
                     xytext=(0, 5),textcoords='offset points',
                     ha='center', va='center', **kwargs)

df = pd.DataFrame(data)
g = sns.FacetGrid(df, col="Platform")
g.map_dataframe(sns.barplot, x="Grade", y="Counts", hue="Colour")
g.map(annotate_bars, fmt='.2g', fontsize=8, color='k')
g.set_axis_labels("Grade", "Counts")
g.add_legend()
g.set_titles(col_template="{col_name}", row_template="{row_name}")