How to get a grouped bar plot of categorical data

Viewed 1781

I have a big dataset with information about students. And I have to build a graph of dependencies between different values. For example, I have two columns "Year" and "School", like picture

which creates a graph something like:

this

my real data

dataset.

I could filter my values, but I have no idea how can I build and combine graphs. It's not working... I found examples looks like this, but I couldn't managed my problem.

The problem is that I need to link the data of one column to the filtered data of the second column, without changing the dataset. I could not find similar solutions.

import pandas as pd


df = pd.read_excel('CREDITATION.xlsx')

plt.title('Depends schools in years')
plt.xlabel('Schools')
plt.ylabel('Counts')
plt.xticks(df['SCHOOL_YEAR_MOBILITY'])
plt.yticks(np.arange(0, 1000, step=100))

bar_width = 0.35



agr2016 = df.loc[(df['SCHOOL'] == 'Escola Superior Agrária de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2016)].count()[0] 
agr2017 = df.loc[(df['SCHOOL'] == 'Escola Superior Agrária de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2017)].count()[0] 
agr2018 = df.loc[(df['SCHOOL'] == 'Escola Superior Agrária de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2018)].count()[0] 
agr2019 = df.loc[(df['SCHOOL'] == 'Escola Superior Agrária de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2019)].count()[0] 
agr2020 = df.loc[(df['SCHOOL'] == 'Escola Superior Agrária de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2020)].count()[0] 

manag2016 = df.loc[(df['SCHOOL'] == 'Escola Superior de Tecnologia e Gestão de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2016)].count()[0]
manag2017 = df.loc[(df['SCHOOL'] == 'Escola Superior de Tecnologia e Gestão de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2017)].count()[0]
manag2018 = df.loc[(df['SCHOOL'] == 'Escola Superior de Tecnologia e Gestão de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2018)].count()[0]
manag2019 = df.loc[(df['SCHOOL'] == 'Escola Superior de Tecnologia e Gestão de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2019)].count()[0]
manag2020 = df.loc[(df['SCHOOL'] == 'Escola Superior de Tecnologia e Gestão de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2020)].count()[0]

com2016 = df.loc[(df['SCHOOL'] == 'Escola Superior de Comunicação, Administração e Turismo')&(df['SCHOOL_YEAR_MOBILITY'] == 2016)].count()[0]
com2017 = df.loc[(df['SCHOOL'] == 'Escola Superior de Comunicação, Administração e Turismo')&(df['SCHOOL_YEAR_MOBILITY'] == 2017)].count()[0]
com2018 = df.loc[(df['SCHOOL'] == 'Escola Superior de Comunicação, Administração e Turismo')&(df['SCHOOL_YEAR_MOBILITY'] == 2018)].count()[0]
com2019 = df.loc[(df['SCHOOL'] == 'Escola Superior de Comunicação, Administração e Turismo')&(df['SCHOOL_YEAR_MOBILITY'] == 2019)].count()[0]
com2020 = df.loc[(df['SCHOOL'] == 'Escola Superior de Comunicação, Administração e Turismo')&(df['SCHOOL_YEAR_MOBILITY'] == 2020)].count()[0]

health2016 = df.loc[(df['SCHOOL'] == 'Escola Superior de Saúde de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2016)].count()[0] 
health2017 = df.loc[(df['SCHOOL'] == 'Escola Superior de Saúde de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2017)].count()[0] 
health2018 = df.loc[(df['SCHOOL'] == 'Escola Superior de Saúde de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2018)].count()[0] 
health2019 = df.loc[(df['SCHOOL'] == 'Escola Superior de Saúde de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2019)].count()[0] 
health2020 = df.loc[(df['SCHOOL'] == 'Escola Superior de Saúde de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2020)].count()[0] 

education2016 = df.loc[(df['SCHOOL'] == 'Escola Superior de Educação de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2016)].count()[0]
education2017 = df.loc[(df['SCHOOL'] == 'Escola Superior de Educação de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2017)].count()[0]
education2018 = df.loc[(df['SCHOOL'] == 'Escola Superior de Educação de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2018)].count()[0]
education2019 = df.loc[(df['SCHOOL'] == 'Escola Superior de Educação de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2019)].count()[0]
education2020 = df.loc[(df['SCHOOL'] == 'Escola Superior de Educação de Bragança')&(df['SCHOOL_YEAR_MOBILITY'] == 2020)].count()[0]

plt.bar() #idk
plt.show()
1 Answers

Imports and Sample Data

import pandas as pd
import seaborn as sns
import numpy as np  # for test data only

np.random.seed(365)
rows = 100
data = {'year': np.random.choice(range(2016, 2021), size=rows),
        'school': np.random.choice(['a', 'b', 'c', 'd', 'e'], size=rows)}
df = pd.DataFrame(data)

# display(df.head())
   year school
0  2018      a
1  2020      b
2  2017      b
3  2019      b
4  2020      c

With seaborn.countplot

# plot and add annotations
p = sns.countplot(data=df, x='year', hue='school')
p.legend(title='School', bbox_to_anchor=(1, 1), loc='upper left')

for c in p.containers:
    # set the bar label
    p.bar_label(c, fmt='%.0f', label_type='edge')

enter image description here

With pandas.DataFrame.plot

dfp = df.pivot_table(index='year', columns='school', values='school', aggfunc='size')

ax = dfp.plot(kind='bar', rot=0)

ax.legend(title='School', bbox_to_anchor=(1, 1), loc='upper left')

for c in ax.containers:
    # set the bar label
    ax.bar_label(c, fmt='%.0f', label_type='edge')

enter image description here

# groupby and pivot
ax = df.groupby(['year']).school.value_counts().reset_index(name='counts').pivot(index='year', columns='school', values='counts').plot(kind='bar')

# crosstab
ax = pd.crosstab(df.year, df.school).plot(kind='bar')
Related