求助:Matplotlib无法同时显示两个独立图表问题
解决Matplotlib多个独立Figure无法同时显示的问题
你的问题出在Matplotlib默认的显示逻辑上:plt.show()默认会阻塞程序运行,必须关闭当前弹出的窗口,才会继续执行后续代码创建并显示第二个Figure。下面给你两种直接解决的办法:
方法1:开启交互模式
在代码开头开启Matplotlib的交互模式,这样每个Figure创建时会立即显示,最后关闭交互模式并调用plt.show()来保持所有窗口不自动关闭:
import matplotlib.pyplot as plt import math # 开启交互模式 plt.ion() 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.ioff() plt.show()
方法2:使用非阻塞的show调用
在第一个Figure创建完成后,用plt.show(block=False)实现非阻塞显示,让程序继续执行创建第二个Figure,最后再调用一次plt.show()阻塞程序,维持所有窗口的显示状态:
import matplotlib.pyplot as plt import math plt.figure(1) plt.plot(piresults) plt.ylabel('value of calculated pi') plt.xlabel('number of fractions calculated') # 非阻塞显示第一个窗口,不中断程序执行 plt.show(block=False) 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()
额外补充:如果想把两个图画在同一个窗口并排显示
如果你的需求是在同一个窗口里并排展示两个图表(而非独立窗口),可以用子图实现,代码示例如下:
import matplotlib.pyplot as plt import math # 创建1行2列的子图布局 fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5)) # 绘制第一个子图 ax1.plot(piresults) ax1.set_ylabel('value of calculated pi') ax1.set_xlabel('number of fractions calculated') # 计算误差值(用列表推导式简化代码) piresults2 = [math.fabs((res - math.pi)/math.pi) for res in piresults] # 绘制第二个子图 ax2.plot(piresults2) ax2.set_ylim(0,1) ax2.set_ylabel('error %') ax2.set_xlabel('number of fractions calculated') # 自动调整子图间距 plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者XtheGxmerz0
相关产品推荐
相关产品推荐

