V_sqrt
V_sqrt

Reputation: 567

Plotting two pie charts one beside another one (subplots)

I would like to plot two pie charts one beside another. I am creating individually them as follows:

pie chart 1:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(4,3),dpi=144)
ax = fig.add_subplot(111)

cts = df1.Name.value_counts().to_frame()
ax.pie(cts.Name)

pie chart 2:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(4,3),dpi=144)
ax = fig.add_subplot(111)

cts = df2.Name.value_counts().to_frame()
ax.pie(cts.Name)

I am not familiar with visualisation in python, but I think I should use subplot to create these two plots.

An example of data is

df1:

  Name

  water
  fire
  water
  fire
  fire
  fire

df2

  Name

  fire
  fire
 stones
 stones
 stones
 stones 

Upvotes: 0

Views: 10700

Answers (3)

PieCot
PieCot

Reputation: 3629

You can use subplots:

import matplotlib.pyplot as plt

colors = {'water': 'b', 'fire': 'r', 'stones': 'gray'}  # same color for each name in both pie
fig, axes = plt.subplots(1, 2, figsize=(4,3),dpi=144)
plt.suptitle("Big title")

for ax, df, title in zip(axes, (df1, df2), ('Title 1', 'Title 2')):
    count = df.Name.value_counts().to_frame().sort_index()
    ax.pie(count.Name, labels=count.index, colors=[colors[c] for c in count.index])
    ax.set_title(title)

enter image description here

Upvotes: 1

bb1
bb1

Reputation: 7863

You need to create two subplots - one for each pie chart. The following code will do it (explanation in comments):

import matplotlib.pyplot as plt

# the same figure for both subplots
fig = plt.figure(figsize=(4,3),dpi=144)

# axes object for the first pie chart 
# fig.add_subplot(121) will create a grid of subplots consisting 
# of one row (the first 1 in (121)), two columns (the 2 in (121)) 
# and place the axes object as the first subplot 
# in the grid (the second 1 in (121))
ax1 = fig.add_subplot(121)

# plot the first pie chart in ax1
cts = df1.Name.value_counts().to_frame()
ax1.pie(cts.Name)

# axes object for the second pie chart 
# fig.add_subplot(122) will place ax2 as the second 
# axes object in the grid of the same shape as specified for ax1 
ax2 = fig.add_subplot(122)

# plot the sencond pie chart in ax2
cts = df2.Name.value_counts().to_frame()
ax2.pie(cts.Name)

plt.show()

This gives:

enter image description here

Upvotes: 1

Jay Patel
Jay Patel

Reputation: 1420

This would do a job. You can defined subplots using fig.add_subplot(row, column, position).

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(4,3),dpi=144)
ax = fig.add_subplot(121)

cts = df1.Name.value_counts().to_frame()
ax.pie(cts.Name)

ax = fig.add_subplot(122)
cts = df2.Name.value_counts().to_frame()
ax.pie(cts.Name)

enter image description here

Upvotes: 1

Related Questions