我有这段代码来生成 pi 的部分和(这是绘制它的部分):
plt.figure(1)
plt.plot(piresults)
plt.ylabel('value of calculated pi')
plt.xlabel('number of fractions calculated')
piresults2=[]
for result in piresults:
piresults2.append(math.fabs((result-math.pi)/math.pi))
plt.figure(2)
plt.plot(piresults2)
plt.ylim(0,1)
plt.ylabel('error %')
plt.xlabel('number of fractions calculated')
plt.show()
但我的问题是这些图不会同时出现
我希望在最后仅使用 plt.show() 并使图形分开后,这两个图会并排出现。但这并没有发生?它们是分开出现的,我必须关闭一个才能得到另一个
如果它们作为单独的窗口弹出,您可以在单个图形/窗口上绘制两个图。
使用
plt.subplots()
创建具有多个子图的图形 (axes
)。依次选择每个子图(axes[0]
,然后axes[1]
)进行绘图。
piresults1 = np.linspace(3.12, 3.16)
piresults2 = np.linspace(0.2, 0.6)
#Create figure with 2 subplots ("axes")
figure, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 3))
#Get the handle of the first subplot, axes[0], and plot
ax = axes[0]
ax.plot(piresults1)
ax.set_ylabel('value of calculated pi')
ax.set_xlabel('number of fractions calculated')
#Get the handle of the second subplot, axes[1], and plot
ax = axes[1]
ax.plot(piresults2)
ax.set_ylim(0,1)
ax.set_ylabel('error %')
ax.set_xlabel('number of fractions calculated')