如何在顶部(catplot seaborn)添加条形值?

时间:2018-10-28 08:19:55

标签: python-2.7 pandas plot bar-chart seaborn

数据采用以下格式:

first_name nick_name              activity                         duration            
  Harish   Escorts   MC GUARD ASSEMBLY WITH CABINATE BRACKET          226   
  Harish   Escorts   COOLANT TANK AND SIDE DOORS, OPP DOORS           225   
Narasaraj  Escorts   MC GUARD ASSEMBLY WITH CABINATE AND BRACKET MO   225   
Narasaraj  Escorts   COOLANT TANK AND SIDE DOORS, OPP DOORS ASSEMBLY  150
PurushothamEscorts   PNEUMATIC AND LUBRICATION ASSEMBLY                55
Shivu      Escorts   CABLE CARRIER AND AXIS MOTOR ASSEMBLY            123

使用seaborn,我正在做一个小程序:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="ticks", color_codes=True)


df = pd.read_excel('VMC & HMC data (sep&oct-15).xlsx',  index = False)

df1 = df1[[ "first_name" , "nick_name", "activity" , "duration"]]

g = sns.catplot(x= 'first_name', y = 'duration', hue = 'activity' , data = df1, kind = 'bar', dodge=False, palette="deep", ci = None)

plt.ylim(0,300)
plt.gcf().autofmt_xdate()

for index, row in df1.iterrows():
    g.text(row.name,row.first_name,row.duration, color='black', ha="center")

它向我抛出错误:

AttributeError: 'FacetGrid' object has no attribute 'text'

如何在条形图的顶部添加条形图的值?? No values at the top of the bar

2 个答案:

答案 0 :(得分:1)

catplot返回FacetGrid。它没有text方法。

两个选项:

A。从网格中选择一个轴

  • 如果catplot产生多个轴

    g = sns.catplot(...)
    g.axes[0].text(...)
    
  • 如果catplot产生单个轴

    g = sns.catplot(...)
    g.axes.text(...)
    

B。使用barplot

ax = sns.barplot(...)
ax.text(...)

答案 1 :(得分:0)

我尝试了选项A并得到了AttributeError:'numpy.ndarray'对象没有属性'text'。

这是我解决的方法: 您可以通过修改返回的Facet网格为每个条添加值。

g = sns.catplot(x='class', y='survival rate', 
            hue='sex', data=df, kind='bar')

ax = g.facet_axis(0,0)
for p in ax.patches:
    ax.text(p.get_x() + 0.015, 
            p.get_height() * 1.02, 
            '{0:.2f}'.format(p.get_height()), 
            color='black', rotation='horizontal', size='large')

catplot example

如果要重新创建图,则示例数据如下所示:

       class    sex   survival rate
   0    first   men    0.914680
   1    second  men    0.300120
   2    third   men    0.118990
   3    first   women  0.667971
   4    second  women   0.329380
   5    third   women   0.189747
   6    first   children    0.660562
   7    second  children    0.882608
   8    third   children    0.121259