0

I am trying to answer in haberman dataset (https://www.kaggle.com/gilsousa/habermans-survival-data-set)

  • what % of the people survive in various age brackets

I have taken following steps after getting data in pandas dataframe 'data'. Not able to create calculated column which has '% survived'. % survived = total survived / total in that age group.

print(data.head(3))

   age  year  nodes  status
0   30    64      1       1
1   30    62      3       1
2   30    65      0       1

data['age group'] = pd.cut(data.age,range(25,85,5))

table = data.pivot_table(index =['age group'], columns = ['status'], values='year',aggfunc=np.count_nonzero).fillna(0)
table.reset_index(level=0, inplace=True)

table['surv_pc'] = table.iloc[:,1]/(table.iloc[:,1]+table.iloc[:,2])*100

sns.set_theme(style="whitegrid")
bar = sns.barplot(data=table, x='age group',y='surv_pc')

enter image description here

the type of graph is matplotlib.axes._subplots.AxesSubplot

How do i access the bar heights so that i can put labels as per plot.text() method ? As per documentation of https://matplotlib.org/3.1.0/api/axes_api.html?highlight=matplotlib#matplotlib.axes.Axes, it returns Axes object only. Please help understand...

Gupta
  • 314
  • 4
  • 17
  • I tried to look inside the bar chart elements but this gives error ---> for elements in bar: print(elements) TypeError: 'AxesSubplot' object is not iterable – Gupta Dec 25 '20 at 17:31
  • 1
    Here are some similar questions: https://stackoverflow.com/questions/43214978/seaborn-barplot-displaying-values, https://stackoverflow.com/questions/31749448/how-to-add-percentages-on-top-of-bars-in-seaborn – ForceBru Dec 25 '20 at 17:35

1 Answers1

1

From the study of other question that @ForceBru suggested what i understood was that all matlplot objects have class "patches" which contains the graph contents. Read more https://matplotlib.org/3.1.0/api/patches_api.html?highlight=patches

to experiment, i tried to iterate through these patches

for bars in bar.patches:
    print(bars)

Rectangle(xy=(-0.4, 0), width=0.8, height=100, angle=0)
Rectangle(xy=(0.6, 0), width=0.8, height=84.6, angle=0)
Rectangle(xy=(1.6, 0), width=0.8, height=92.6, angle=0)
Rectangle(xy=(2.6, 0), width=0.8, height=67.4, angle=0)
Rectangle(xy=(3.6, 0), width=0.8, height=70.2, angle=0)
...
...

then i did actual implementation, as in:
(refer to here)

for bars in bar.patches:
    bar.text(bars.get_x(),bars.get_height(),bars.get_height()) 

I got the graph as below

enter image description here

Gupta
  • 314
  • 4
  • 17