Pycharm中使用matplotlib绘制动态图形

Pycharm中使用matplotlib绘制动态图形

最近用pycharm学习D2L时发现官方在jupyter notebook交互式环境中能动态绘制图形,但是在pycharm脚本环境中只会在最终 plt.show() 后输出一张静态图像。于是有了下面这段自己折腾了一下午的代码,用来在pycharm中模仿jupyter交互式环境的动态绘制图像:

python 复制代码
import matplotlib
import matplotlib.pyplot as plt
from IPython.display import display, clear_output
import time

matplotlib.use('Qt5Agg')
plt.ion()
fig, ax = plt.subplots()
ax.set_title("ECG Signal")
plt.xlabel("time: s")
plt.ylabel("voltage")
#############################
# 1:直接绘制完整波形:
# ax.plot(signal)
# ax.legend(["MLII", "V5"])
# plt.show()
#############################
# 2:随时间动态输出波形:
y1 = []
y2 = []
t = []
sr = 360  # 采样率
plt.xticks(range(0, len(signal) // sr + 1))
for n in range(len(signal)):
    y1.append(signal[n, 0])
    y2.append(signal[n, 1])
    t.append(n / sr)
    if (n + 1) % 10 == 0 or (n + 1) == len(signal):
        time.sleep(0.01)
        ax.plot(t, y1, "-", color='deepskyblue', linewidth=1)      
        clear_output(wait=True)
        display(fig)
        plt.pause(0.01)
ax.legend(["MLII", "V5"])
plt.show()

最终效果

相关推荐
2601_962078194 小时前
Python中calendar.weekday用法
python·编程技巧·calendar·日期处理·weekday
2601_962218614 小时前
万象生鲜系统业财一体化底层打通技术自动生成经营账单
大数据·数据库·人工智能·python·算法
2601_966949654 小时前
为什么量化策略需要大量历史股票数据?从回测可信度理解数据规模
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
2601_962885724 小时前
如何用 Python 扫描 A 股跳空缺口并统计缺口回补概率?
java·前端·python
李高钢5 小时前
Python FastAPI 框架入门:从零搭建你的第一个高性能 API 服务
数据库·python·fastapi
ocean21035 小时前
2025-2026年Python面试高频知识点洞察
开发语言·python·面试·python八股文
Warson_L6 小时前
Python的OrderedDict
python
隐擎fox6 小时前
高性能网络爬虫架构设计:基于 Python 的长连接复用与分布式会话池调度实践
分布式·python·网络协议·tcp/ip·高并发·网络爬虫、
Warson_L6 小时前
Python的TypedDict
python·langchain·llm
晓窗科技7 小时前
口碑好的AI基座服务商
大数据·人工智能·python