How to plot multiple pie chart or bar chart from multi-index dataframe?
Question:
Dataframe is as below.
There are multiple index as category_1
& category_2
and two column as count
& %
I need to draw multiple (for each category_1
) pie chart for category_2
& %
and bar chart for category_2
& count
.
count
%
category_1
category_2
Bady and Kids
Baby Care
220
27.5
Toys
176
22
Boys Clothing
156
19.5
Girls Clothing
144
18
Baby Boy Clothing
104
13
Women’s wear
Party Dresses
224
28
Sports Wear
188
23.5
Swim wear
140
17.5
Winter Wear
128
16
Watches
120
15
Answers:
You can use:
#gt number of groups first for subplots
no = len(df.index.levels[0])
fig, axes = plt.subplots(no, 2, figsize=(10, 6))
#for each group by first level of Multiindex
for i, (name, g) in enumerate(df.groupby(level=0)):
#remove first level and index name
g = g.droplevel(0).rename_axis(None)
#get positions dynamic
ax = axes[i, 0]
ax1 = axes[i, 1]
#plot both graphs together
g['count'].plot.pie(ax=ax, legend=False)
ax.set_title(f'{name} %')
g['%'].plot.bar(ax=ax1, legend=False, rot=45)
ax1.set_title(f'{name} count')
fig.subplots_adjust(wspace=.2)
You can use the following code to plot pie charts and bar charts for each category_1 in your multi-index dataframe:
import pandas as pd
import matplotlib.pyplot as plt
# create a sample dataframe
data = {
('Bady and Kids', 'Baby Care'): (220, 27.5),
('Bady and Kids', 'Toys'): (176, 22),
('Bady and Kids', 'Boys Clothing'): (156, 19.5),
('Bady and Kids', 'Girls Clothing'): (144, 18),
('Bady and Kids', 'Baby Boy Clothing'): (104, 13),
("Women's wear", 'Party Dresses'): (224, 28),
("Women's wear", 'Sports Wear'): (188, 23.5),
("Women's wear", 'Swim wear'): (140, 17.5),
("Women's wear", 'Winter Wear'): (128, 16),
("Women's wear", 'Watches'): (120, 15)
}
df = pd.DataFrame(data.values(), index=pd.MultiIndex.from_tuples(data.keys(), names=['category_1', 'category_2']), columns=['count', '%'])
# plot pie charts and bar charts for each category_1
for category_1 in df.index.get_level_values(0).unique():
sub_df = df.loc[category_1]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))
sub_df.plot(kind='pie', y='%', legend=None, ax=ax1)
ax1.set_title(f'{category_1} - %')
sub_df.plot(kind='bar', y='count', legend=None, ax=ax2)
ax2.set_title(f'{category_1} - count')
plt.show()
This code creates a loop to iterate through each unique value of category_1. Inside the loop, it extracts a sub-dataframe for the current category_1 and then plots a pie chart for the % column and a bar chart for the count column using sub_df.plot(). Finally, it sets the title of each chart and shows them using plt.show().
This will output a set of pie charts and bar charts, one for each unique category_1.
You can use:
for cat1, subdf in df.groupby(level='category_1'):
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))
subdf.loc[cat1, :].plot.pie(y='count', ax=ax1, ylabel='', legend=False)
subdf.loc[cat1, :].plot.bar(y='%', ax=ax2, rot=45, xlabel='', legend=False)
fig.suptitle(cat1)
fig.tight_layout()
plt.show()
Output:
Dataframe is as below.
There are multiple index as category_1
& category_2
and two column as count
& %
I need to draw multiple (for each category_1
) pie chart for category_2
& %
and bar chart for category_2
& count
.
count | % | ||
---|---|---|---|
category_1 | category_2 | ||
Bady and Kids | Baby Care | 220 | 27.5 |
Toys | 176 | 22 | |
Boys Clothing | 156 | 19.5 | |
Girls Clothing | 144 | 18 | |
Baby Boy Clothing | 104 | 13 | |
Women’s wear | Party Dresses | 224 | 28 |
Sports Wear | 188 | 23.5 | |
Swim wear | 140 | 17.5 | |
Winter Wear | 128 | 16 | |
Watches | 120 | 15 |
You can use:
#gt number of groups first for subplots
no = len(df.index.levels[0])
fig, axes = plt.subplots(no, 2, figsize=(10, 6))
#for each group by first level of Multiindex
for i, (name, g) in enumerate(df.groupby(level=0)):
#remove first level and index name
g = g.droplevel(0).rename_axis(None)
#get positions dynamic
ax = axes[i, 0]
ax1 = axes[i, 1]
#plot both graphs together
g['count'].plot.pie(ax=ax, legend=False)
ax.set_title(f'{name} %')
g['%'].plot.bar(ax=ax1, legend=False, rot=45)
ax1.set_title(f'{name} count')
fig.subplots_adjust(wspace=.2)
You can use the following code to plot pie charts and bar charts for each category_1 in your multi-index dataframe:
import pandas as pd
import matplotlib.pyplot as plt
# create a sample dataframe
data = {
('Bady and Kids', 'Baby Care'): (220, 27.5),
('Bady and Kids', 'Toys'): (176, 22),
('Bady and Kids', 'Boys Clothing'): (156, 19.5),
('Bady and Kids', 'Girls Clothing'): (144, 18),
('Bady and Kids', 'Baby Boy Clothing'): (104, 13),
("Women's wear", 'Party Dresses'): (224, 28),
("Women's wear", 'Sports Wear'): (188, 23.5),
("Women's wear", 'Swim wear'): (140, 17.5),
("Women's wear", 'Winter Wear'): (128, 16),
("Women's wear", 'Watches'): (120, 15)
}
df = pd.DataFrame(data.values(), index=pd.MultiIndex.from_tuples(data.keys(), names=['category_1', 'category_2']), columns=['count', '%'])
# plot pie charts and bar charts for each category_1
for category_1 in df.index.get_level_values(0).unique():
sub_df = df.loc[category_1]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))
sub_df.plot(kind='pie', y='%', legend=None, ax=ax1)
ax1.set_title(f'{category_1} - %')
sub_df.plot(kind='bar', y='count', legend=None, ax=ax2)
ax2.set_title(f'{category_1} - count')
plt.show()
This code creates a loop to iterate through each unique value of category_1. Inside the loop, it extracts a sub-dataframe for the current category_1 and then plots a pie chart for the % column and a bar chart for the count column using sub_df.plot(). Finally, it sets the title of each chart and shows them using plt.show().
This will output a set of pie charts and bar charts, one for each unique category_1.
You can use:
for cat1, subdf in df.groupby(level='category_1'):
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))
subdf.loc[cat1, :].plot.pie(y='count', ax=ax1, ylabel='', legend=False)
subdf.loc[cat1, :].plot.bar(y='%', ax=ax2, rot=45, xlabel='', legend=False)
fig.suptitle(cat1)
fig.tight_layout()
plt.show()
Output: