繁体   English   中英

使用 Qt 后端动态更新 Jupyter notebook 中的 matplotlib 图

[英]Dynamically update matplotlib figure in Jupyter notebook with Qt backend

我想在 Jupyter 笔记本中使用PyQt后端动态更新matplotlib图。 但是,window 冻结,只有在执行完整的单元格后,才会显示 window。

如果您知道 Qt 的行为,这很容易实现。 您使用QApplication.processEvents()激活事件循环处理程序,以便显示和处理 window。 你在每次迭代中都调用它,瞧!

示例代码:

import matplotlib.pyplot as plt
from time import sleep
from PyQt5.QtWidgets import QApplication

%matplotlib qt

# Create a Figure with 10 bars of height 0
fig = plt.figure()
ax = plt.subplot(111)
vals = np.zeros(10)
bars = plt.bar(np.arange(len(vals)), vals)
plt.show()

# Iterate 20x
for i in range(20):
    # Generate some data    
    idx = np.random.randint(0,10)
    vals[idx] += 1

    # Adjust bars and y-lim
    bars[idx].set_height(vals[idx])
    plt.ylim([0, max(vals)+1])

    # Draw scene and update Qt!
    fig.canvas.draw()
    QApplication.processEvents()

    # Some artificial delay
    sleep(0.5)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM