How to Create a Stacked Bar Chart in Pandas

You can use the following basic syntax to create a stacked bar chart in pandas:

df.groupby(['var1', 'var2']).size().unstack().plot(kind='bar', stacked=True)

The following example shows how to use this syntax in practice.

Example: Create Stacked Bar Chart in Pandas

Suppose we have the following pandas DataFrame that contains information about various basketball players:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
                   'position': ['G', 'G', 'F', 'F', 'G', 'F', 'F', 'F'],
                   'points': [5, 7, 7, 9, 12, 9, 9, 4]})

#view DataFrame

  team position  points
0    A        G       5
1    A        G       7
2    A        F       7
3    A        F       9
4    B        G      12
5    B        F       9
6    B        F       9
7    B        F       4

We can use the following code to create a stacked bar chart that displays the total count of position, grouped by team:

df.groupby(['team', 'position']).size().unstack().plot(kind='bar', stacked=True)

The x-axis shows the team name and the y-axis shows the total count of position for each team.

From the chart we can see that team A has 2 guards (G) and 2 forwards (F) while team B has 1 guard and 3 forwards.

We can also use the color and title arguments to modify the color of the bars and add a title to the chart:

df.groupby(['team', 'position']).size().unstack().plot(kind='bar', stacked=True,
            color=['steelblue','pink'], title='Position Count by Team')

stacked bar chart in pandas

A title has been added to the top of the plot and the colors of the bars have been changed to steelblue and pink, just as we specified.

Additional Resources

The following tutorials explain how to create other common charts in Python:

How to Create Heatmaps in Python
How to Create a Bell Curve in Python
How to Create an Ogive Graph in Python

Leave a Reply

Your email address will not be published. Required fields are marked *