0

I'm trying to create a seaborn bar graph with values different from the bar value shown at the top. For example, I want the graph to show the height of Bob but list his age on top of his bar.

I've tried using a for loop which listed everyone's age or only one element when I list the index, and I've tired a map function which did the same thing.

import pandas as pd
import numpy as np
import seaborn as sns
sns.set(style="whitegrid")
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (12.0, 10.0)


data = {'name': ['bob', 'mike', 'sam', 'robert', 'amy', 'sarah', 'jessica'], 
        'height(inches)': [72, 68, 71, 68, 74, 69, 74], 
        'age': [23, 24, 30, 25, 28, 25, 21]}

df = pd.DataFrame(data=data)

sns.barplot(x='name', y='height(inches)', data=df)
plt.xticks(rotation=90)

# Get current axis on current figure
ax = plt.gca()

for p in ax.patches:
    age = df['age'].values
    i = map(lambda x: x, age)
    ax.text(p.get_x() + p.get_width()/2., p.get_height(), age, ha='center', va='center')

Here is a link to the image (need 10 reputation points to post of stackoverflow) (https://i.stack.imgur.com/ykIZG.png)

What I would like is to have 23 on top of Bob's graph, 24 on top of Mike's graph, and so on.

There is a similar questions here (How to add percentages on top of bars in seaborn?) which I tried to follow/change to make it work for my code. Still having troubles. I'm fairly new to python and coding in general so I would appreciate any help I can get. Thanks.

MasoodQaim
  • 47
  • 6

1 Answers1

0

Under the assumption that the bars are ordered the same as in the dataframe, it would be

for p, age in zip(ax.patches, df['age'].values):
    ax.text(p.get_x() + p.get_width()/2., p.get_height(), age, 
            ha='center', va='bottom')
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712