使用matplotlib绘制多个饼图
我想用matplotlib同时显示两个图表。
但是我必须先关闭一个图表,才能看到另一个图表。有没有办法同时显示两个或更多的图表呢?
这是我的代码
num_pass=np.size(data[0::,1].astype(np.float))
num_survive=np.sum(data[0::,1].astype(np.float))
prop=num_survive/num_pass
num_dead=num_pass-num_survive
#print num_dead
labels='Dead','Survived'
sizes=[num_dead,num_survive]
colors=['darkorange','green']
mp.axis('equal')
mp.title('Titanic Survival Chart')
mp.pie(sizes, explode=(0.02,0), labels=labels,colors=colors,autopct='%1.1f%%', shadow=True, startangle=90)
mp.show()
women_only_stats = data[0::,4] == "female"
men_only_stats = data[0::,4] != "female"
# Using the index from above we select the females and males separately
women_onboard = data[women_only_stats,1].astype(np.float)
men_onboard = data[men_only_stats,1].astype(np.float)
labels='Men','Women'
sizes=[np.sum(women_onboard),np.sum(men_onboard)]
colors=['purple','red']
mp.axis('equal')
mp.title('People on board')
mp.pie(sizes, explode=(0.01,0), labels=labels,colors=colors,autopct='%1.1f%%', shadow=True, startangle=90)
mp.show()
我该怎么才能同时显示这两个图表呢?
4 个回答
1
是的。User:Banana
的这个回答对我有效。
我有4个图表,当我运行 plt.show()
时,这4个图表都作为独立的饼图显示出来,所以我觉得你可以使用任意数量的figure编号。
plt.figure(0) # Create first chart here and specify all parameters below.
plt.figure(1) # Create second chart here and specify all parameters below.
plt.figure(3) # Create third chart here and specify all parameters below.
plt.figure(4) # Create fourth chart here and specify all parameters below.
plt.show() # show all figures.
2
另外,你可以在同一个图上放多个饼图,方法是使用子图或者多个坐标轴:
mp.subplot(211)
mp.pie(..)
mp.subplot(212)
mp.pie(...)
mp.show()
13
除了Banana的回答,你还可以在同一个图形中用不同的子图来绘制它们:
from matplotlib import pyplot as plt
import numpy as np
data1 = np.array([0.9, 0.1])
data2 = np.array([0.6, 0.4])
# create a figure with two subplots
fig, (ax1, ax2) = plt.subplots(1, 2)
# plot each pie chart in a separate subplot
ax1.pie(data1)
ax2.pie(data2)
plt.show()
14
有几种方法可以做到这一点,最简单的就是使用多个图形编号。你只需要告诉 matplotlib
你正在处理不同的图形,然后同时显示它们就可以了:
import matplotlib.pyplot as plt
plt.figure(0)
# Create first chart here.
plt.figure(1)
# Create second chart here.
plt.show() #show all figures