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

最终效果

相关推荐
xiaopengbc3 分钟前
在 Python 中实现观察者模式的具体步骤是什么?
开发语言·python·观察者模式
Python大数据分析@9 分钟前
python用selenium怎么规避检测?
开发语言·python·selenium·网络爬虫
ThreeAu.12 分钟前
Miniconda3搭建Selenium的python虚拟环境全攻略
开发语言·python·selenium·minicoda·python环境配置
偷心伊普西隆20 分钟前
Python EXCEL 理论探究:格式转换时处理缺失值方法
python·excel
精灵vector1 小时前
LLMCompiler:基于LangGraph的并行化Agent架构高效实现
人工智能·python·langchain
java1234_小锋1 小时前
Scikit-learn Python机器学习 - 特征降维 压缩数据 - 特征选择 - 移除低方差特征(VarianceThreshold)
python·机器学习·scikit-learn
万邦科技Lafite2 小时前
实战演练:通过API获取商品详情并展示
大数据·数据库·python·开放api接口
愈努力俞幸运2 小时前
uv教程 虚拟环境
python·uv