How to plot multiple pie chart in Pandas?

Viewed 27

I selected categories from my data frame, please, see below, and need to plot pie charts for all categories. However, all data are plotted together on a single chart. Do you have any suggestions on how to solve it?

num_var = census.select_dtypes(include=['number']).columns.tolist()

num_var

['age', 'det_ind_code', 'det_occ_code', 'wage_per_hour', 'capital_gains', 'capital_losses', 'stock_dividends', 'continuous_?', 'num_emp', 'own_or_self', 'vet_benefits', 'weeks_worked', 'year']

for item in cat_var:
    census[item].value_counts().plot.pie(figsize=(10,10), fontsize=10, autopct="%.1f")

    plt.gca().set_aspect('equal')
1 Answers

I am just guessing you wanted to define cat_var, not num_var, right?

You did not share your data, so I created a small data frame census for demonstration purposes.

import pandas as pd
import matplotlib.pyplot as plt

census = pd.DataFrame({
    'country': ['CZ', 'CZ', 'CZ', 'DE', 'DE'],
    'age_group': ['0-18', '19-40', '40-65', '65-', '65-'],
    'job': ['astronaut', 'doctor', 'doctor', 'astronaut', 'astronaut']
})
census

To get all categorical variables, you might use

cat_var = census.select_dtypes(include=['object']).columns.tolist()
cat_var

And to get a plot with several pie subplots, use the followig...

for i, var in enumerate(cat_var):
    plt.subplot(1, len(cat_var), i+1)
    census[var].value_counts().plot.pie(fontsize=10, figsize=(10,10), autopct="%.1f")
    plt.gca().set_aspect('equal')

plt.show()
Related