If you only have categorical data and want to create a pie chart matplotlib, you’ll need to convert and summarise your data into a “percentage distribution” or a summary of the data.
By doing so you can create a percentage distribution that can be plotted by matplotlib.
Below we’ll show you an example of how we did it with only categorical data.
import pandas as pd from matplotlib.pyplot import pie, axis, show df = pd.DataFrame( [['Male'], ['Female'], ['Male'], ['Male']], columns=['Gender']) df.groupby('Gender').size().plot(kind='pie', autopct='%.2f')
Line 1 – 2: Import our packages
Line 4: Create our dataset
Line 11: Using dataframe’s
size function, we’re able to count the number of female and males in our dataset, then using the
plot function, we can plot a pie chart based on percentages.