Python Forum

Full Version: Add % on bar chart Matplotlib
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I have started learning Python a month ago and need some help to complete my bar chart with Matplotlib.
I was able to display the bar chart with everything I want on it, besides the percentages on each bar.
The % I am trying to calculate for each bar are related to the total number of participants of a study (2,233 participants in total).

Here the link to the data I have been using for the bar chart:

Data for Bar Chart


Here my code:

# import of libraries
 
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns


# Bar chart building

df_interested = pd.read_csv('https://cocl.us/datascience_survey_data')
interested = df_interested.sort_values(['Very interested'], ascending = False, axis = 0, inplace = True)
df_interested.plot(kind = 'bar', figsize = (20,8), width = 0.8, color=['#5cb85c', '#5bc0de', '#d9534f'])
plt.title('Pourcentage of respondents interest in Data Science Areas', size = 16)
plt.legend(prop={"size":14})

percent_of_goal = ["{}%".format(int(100.*row.interested/2233)) for name,row in df_interested.sort_values.iterrows()]
 
for i,child in enumerate(ax.get_children()[:df_interested.sort_values.index.size]):
 ax.text(i,child.get_bbox().y1+200,percent_of_goal[i], horizontalalignment ='center')


sns.despine()
sns.despine(top=True, right=True, left=True, bottom=False)

plt.xlabel("X Label")
plt.ylabel("Y Label")
ax = plt.gca()
ax.axes.xaxis.set_visible(False)
ax.axes.yaxis.set_visible(False)
plt.grid(True)

plt.show()
This is the error message I get:


AttributeError Traceback (most recent call last)
<ipython-input-4-a2cd6f808608> in <module>
5 plt.legend(prop={"size":14})
6
----> 7 percent_of_goal = ["{}%".format(int(100.*row.interested/2233)) for name,row in df_interested.sort_values.iterrows()]
8
9 for i,child in enumerate(ax.get_children()[:df_interested.sort_values.index.size]):

AttributeError: 'function' object has no attribute 'iterrows'



Thanks in advance for your big help.
I have tried everything. Nothing helps. Completely blocked here.