如何用PyScript依次显示20张Matplotlib图表并停在最后一张?
问题:PyScript循环生成Matplotlib图表无法依次显示
我是PyScript新手,现有代码可正常显示单张Matplotlib图表,但尝试循环生成20张图表并依次显示后停在最后一张时遇到问题:
- 旧版PyScript循环代码无任何输出;
- 替换为
plt.show()无效,尝试IPython.display出现ModuleNotFoundError: No module named 'termios'; - 更新到新版PyScript后,使用
time.sleep(1)仅显示最后一张图表。
原因分析
time.sleep()会阻塞PyScript的主线程,导致浏览器UI无法实时更新,所有图表的渲染都在循环结束后才执行,因此只能看到最后一张。
解决方案
使用PyScript支持的异步编程方式,用asyncio.sleep()替代time.sleep(),让UI在每次等待时能完成更新:
- 导入
asyncio库; - 将绘图逻辑封装为异步函数;
- 使用
await asyncio.sleep(1)替代time.sleep(1),避免阻塞主线程; - 调用异步函数执行循环绘图。
修正后的完整代码
<html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> <script defer src="https://pyscript.net/latest/pyscript.js"></script> <py-config> packages = ["matplotlib", "numpy"] </py-config> </head> <body> <div id="graph-area"></div> <py-script> import matplotlib.pyplot as plt import numpy as np import asyncio async def plot_sequence(): for step in range(20): # 创建新的图表对象 fig, ax = plt.subplots() year_1 = [2016, 2017, 2018, 2019, 2020, 2021] population_1 = np.random.randint(20, size=6) ax.plot(year_1, population_1, marker='o', linestyle='--', color='g', label='Country 1') ax.set_xlabel('Year') ax.set_ylabel('Population (M)') ax.set_title(f'Year vs Population - Step {step+1}') ax.legend(loc='lower right') # 显示当前图表,覆盖之前的内容 display(fig, target="graph-area", append=False) # 异步等待1秒,让UI有时间更新 await asyncio.sleep(1) # 清除当前图表资源 plt.close(fig) # 执行异步绘图函数 await plot_sequence() </py-script> </body> </html>
关键改动说明
- 使用
async def定义异步函数plot_sequence,确保代码可以异步执行; - 用
await asyncio.sleep(1)替代time.sleep(1),释放主线程让浏览器更新UI; - 每次循环创建新的
fig对象,并在完成后用plt.close(fig)清理资源,避免内存泄漏; - 将
plt.xxx改为ax.xxx,使用面向对象的Matplotlib API,避免全局状态干扰。
内容的提问来源于stack exchange,提问作者blindeyes
相关产品推荐
相关产品推荐

