简体   繁体   English

如何使用刻面创建条形图并使用Seaborn添加标签

[英]How to create barplot with facet and add labels with seaborn

I have the following dataframe 我有以下dataframe

import pandas as pd    
df = pd.DataFrame({'reg' : ['A', 'B', 'C'],
                   'file': ['1', '1', '2'],
                   'val' : [1, 2, 3]})

I would like to create a barplot using seaborn , with faceting by file , color by reg and also add the val on top of each bar 我想使用seaborn创建一个barplot ,按file进行seaborn faceting ,按reg颜色设置,并在每个bar的顶部添加val

I have tried this 我已经试过了

  import seaborn as sns
  g = sns.FacetGrid(df, col='file', hue='reg', col_wrap=2)
  g.map(sns.barplot, 'reg', 'val').add_legend()
  g.savefig('test_so.png')

But, this doesn't do the coloring right 但是,这不会正确着色

Any ideas? 有任何想法吗?

You need order parameter, add unique per @jdehesa mentions below: 您需要order参数,为每个@jdehesa添加unique ,如下所示:

g = sns.FacetGrid(df, col='file', hue='reg', col_wrap=2)
g.map(sns.barplot, 'reg', 'val', order=df.reg.unique()).add_legend()

Output: 输出:

在此处输入图片说明


Add labels to bars in facetgrid plot 在Facetgrid图中的条形上添加标签

g = sns.FacetGrid(df, col='file', hue='reg', col_wrap=2)
g.map(sns.barplot, 'reg', 'val', order=df.reg.unique()).add_legend()

for ax in g.axes:
    for p in ax.patches:
             ax.annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()),
                 ha='center', va='center', fontsize=11, color='black', xytext=(0, 5),
                 textcoords='offset points')

Output: 输出: 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM