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()

最终效果

相关推荐
1***s63215 小时前
Python爬虫反爬策略,User-Agent与代理IP
开发语言·爬虫·python
咖啡の猫16 小时前
Python的自述
开发语言·python
重启编程之路17 小时前
python 基础学习socket -TCP编程
网络·python·学习·tcp/ip
云和数据.ChenGuang18 小时前
pycharm怎么将背景换成白色
ide·python·pycharm
achi01018 小时前
Ubuntu 24.04 一站式 Flask 生产部署:pyenv + PyCharm + Gunicorn + Nginx + systemd
pycharm·flask·systemd·gunicorn·pyenv·ubuntu 24.04·生产部署
我的xiaodoujiao18 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 25--数据驱动--参数化处理 Excel 文件 2
前端·python·学习·测试工具·ui·pytest
DO_Community19 小时前
基于AI Agent模板:快速生成 SQL 测试数据
人工智能·python·sql·ai·llm·ai编程
Q_Q51100828520 小时前
python+django/flask的宠物用品系统vue
spring boot·python·django·flask·node.js·php