0
votes

Suppose I have a data frame df

df =

Name   Percentage  No. of Subjects
Sai    90          4
Kiran  84          2
Karan  26          5
Teja   70          5

I am interested in plotting a bar graph showing the df['No. of Subjects'] on the x-axis, df['Percentage'] on the y-axis and df['Name'] as Bars with a legend.

Expected Schematic Output looks like :) :

enter image description here

2

2 Answers

2
votes
import pandas as pd
import seaborn as sns

df = pd.DataFrame( [{"Name":"Sai", "Percentage":90, "No. of Subjects":4},
{"Name":"Kiran", "Percentage":84, "No. of Subjects":2},
{"Name":"Karan", "Percentage":26, "No. of Subjects":5},
{"Name":"Teja", "Percentage":70, "No. of Subjects":5}] ) 

ax = sns.barplot(x="Name", y="Percentage", hue="No. of Subjects", data=df, dodge=False)

#You can try without those next lines, but need them on my mac
import matplotlib.pyplot as plt 
plt.show()

It make more sense to plot with name in the x axis. As you have 2 students with the same No of subjects, the function barplot will understand it in a different way.

enter image description here

Please have a look at the very good doc of seaborn for bar plot, it is full of exemples !

Best, R

2
votes

A seaborn barplot can be used to draw the bars. The hue parameter is responsible to color each bar and create entries for an accompanying legend with the names.

To get the 'No. of Subjects' in the xtick labels, they can be set explicitly.

import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns

df = pd.DataFrame({'Name': ['Sai', 'Kiran', 'Karan', 'Teja'],
                   'Percentage': [90, 84, 26, 70],
                   'No. of Subjects': [4, 2, 5, 5]})
ax = sns.barplot(x='Name', y='Percentage', hue='Name', dodge=False, data=df)
ax.set_xticklabels(df['No. of Subjects'])
ax.set_xlabel('No. of Subjects')
ax.set_ylim(0, 100)
ax.legend(loc='upper left', bbox_to_anchor=(1.01, 1.05))
for i, perc in enumerate(df['Percentage']):
    ax.text(i, perc, f'{perc:.0f} %\n', ha='center', va='center', size=15)
plt.tight_layout()
plt.show()

resulting plot