我想绘制两个并排的饼图。 我按如下方式单独创建它们:
饼图 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)
饼图 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)
我不熟悉python中的可视化,但我认为我应该使用subplot来创建这两个图。
数据的一个例子是
df1:
Name
water
fire
water
fire
fire
fire
df2
Name
fire
fire
stones
stones
stones
stones
答案 0 :(得分:1)
您需要创建两个子图 - 每个饼图一个。以下代码将完成(注释中的解释):
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()
这给出:
答案 1 :(得分:1)
这会起作用。您可以使用 subplots
定义 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)
答案 2 :(得分:1)
您可以使用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)