You can use the following methods to create a bar plot to visualize the counts in a pandas crosstab:
Method 1: Create Grouped Bar Plot
import matplotlib.pyplot as plt my_crosstab.plot(kind='bar')
Method 2: Create Stacked Bar Plot
import matplotlib.pyplot as plt my_crosstab.plot(kind='bar', stacked=True)
The following examples show how to use each of these methods in practice with the following pandas crosstab:
import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C'], 'position':['G', 'G', 'F', 'G', 'F', 'F', 'F', 'G', 'G', 'F', 'F'], 'points': [22, 25, 24, 39, 34, 20, 18, 17, 20, 19, 22]}) #create crosstab to display count of players by team and position my_crosstab = pd.crosstab(df.team, df.position) #view crosstab print(my_crosstab) position F G team A 1 2 B 3 1 C 2 2
Example 1: Create Grouped Bar Plot from Crosstab
We can use the following syntax to create a grouped bar plot from the crosstab:
import matplotlib.pyplot as plt #create grouped bar plot my_crosstab.plot(kind='bar', rot=0)
Note: The argument rot=0 rotates that x-axis labels 90 degrees to make them easier to read.
The x-axis displays the team names while the grouped bars display the frequency count of each position.
For example, we can see:
- There is 1 player on team A with a position of F.
- There are 2 players on team A with a position of G.
And so on.
Example 2: Create Stacked Bar Plot from Crosstab
We can use the following syntax to create a stacked bar plot from the crosstab:
import matplotlib.pyplot as plt #create stacked bar plot my_crosstab.plot(kind='bar', stacked=True, rot=0)
Note: The argument stacked=True allowed us to create a stacked bar plot instead of a grouped bar plot.
The x-axis displays the team names while the stacked bars display the frequency count of each position.
For example, we can see:
- There is 1 player on team A with a position of F.
- There are 2 players on team A with a position of G.
- There are 3 total players on team A.
And so on.
This type of plot is particularly useful when we want to visualize the total count of elements for each unique value on the x-axis.
Note: You can find the complete documentation for the pandas crosstab() function here.
Additional Resources
The following tutorials explain how to perform other common tasks in pandas:
Pandas: How to Create Crosstab with Percentages
Pandas: How to Use aggfunc in crosstab() Function
Pandas: How to Annotate Bars in Bar Plot