How to plot a stacked bar chart in Pandas?

Step 1: Arrange your DataFrame

First step will be create a simple DataFrame containing the data that you would like to plot. In our case those would be random figures in a hiring campaign.

import pandas as pd
area = ['Java', 'R', 'Python', 'Javascript', 'Python']
applications = [150, 168, 158, 75, 98]
hired = [17,14, 17, 12, 15]
campaign = dict(area = area, hired = hired, applications  = applications )
hrdf = pd.DataFrame(data=campaign)

Let’s loo into the data:


Our goal will be to create a simple stacked plot showing the number of hired vs applicants for every programming language. Looking inot the DataFrame rows we can see that we have a couple of rows (indexes 2 and 4) that pertain to the Python area.

Hence we will first group our DataFrame rows by area:

hr_grp = hrdf.groupby(['area']).sum()

Here’s our group data:


Step 2: Render your bar chart with Pandas

Now, we’ll render our chart. As Pandas contains some basic matplotlib capability, we don’t need to import matplotlib or Seaborn to render simple charts.

hr_grp.plot(kind='bar', stacked = True, title= 'Hired vs applications by Area');

Here’s our chart:

Note the usage of the stacked=True parameter. Otherwise the columns will show up once next to the other.

hr_grp.plot(kind='bar', title= 'Hired vs applications by Area');

Step 3: Customize your stacked plot

Now it is time to fix up the loo and feel of our chart. We will change the chart color, re-position the legend and tide up our chart axis.

bar_chart = hr_grp.plot(kind='bar', stacked = True, cmap = 'viridis', title= 'Hired vs applications by Area') #1 

bar_chart.legend(bbox_to_anchor= (1.3, 1)) #2 
bar_chart.set_xlabel ('Programming Language', fontsize = 13); #3
bar_chart.set_ylabel ('Hired vs Applicants', fontsize = 13); #4 

Here’s our nice stacked chart:


  • #1 – setting your chart color map.
  • #2 – repositioning the legend
  • #3 – setting the x label content and font
  • #4 – setting the y label content and font

Related Learning

How to create a pie chart with the pandas library?