【问题标题】:Automatically updated graph in jupyter notebook using qt5使用 qt5 在 jupyter notebook 中自动更新图形
【发布时间】:2017-05-17 13:50:15
【问题描述】:

如何在 jupyter notebook 中做到这一点:

%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt

m = 100
n = 100
matrix = np.random.normal(0,1,m*n).reshape(m,n)

fig = plt.figure()
ax = fig.add_subplot(111)
plt.ion()

fig.show()
fig.canvas.draw()

for i in range(0,100):
   #ax.clear()
   plt.plot(matrix[i,:])
   fig.canvas.draw()

但是使用“%matplotlib qt5”而不是“notebook”?

当我尝试它时,它仅在循环结束后显示图形。我希望看到它更新每一个情节。

【问题讨论】:

    标签: python matplotlib qt5 jupyter


    【解决方案1】:

    原则上您可以在交互模式下执行以下操作:

    %matplotlib qt4
    import numpy as np
    import matplotlib.pyplot as plt
    
    m = 100
    n = 100
    matrix = np.random.normal(0,1,m*n).reshape(m,n)
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.ion()
    
    plt.draw()
    
    
    for i in range(0,30):
       #ax.clear()
       plt.plot(matrix[i,:])
       plt.draw()
       plt.pause(0.1)
    plt.ioff()
    plt.show()
    

    但是,由于使用了 Qt,它可能会在完成循环后在 jupyter 中崩溃。 但是,当使用 tk 后端时,它应该可以工作,%matplotlib tk

    您可能需要考虑使用FuncAnimation 而不是交互模式。虽然这会受到与 Jupyter 中 Qt 相同的限制,但我发现使用函数更新绘图更直观,并且无需手动重绘画布。

    %matplotlib tk
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.animation 
    
    m = 100
    n = 100
    matrix = np.random.normal(0,1,m*n).reshape(m,n)
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    
    def update(i):
        #ax.clear()
        plt.plot(matrix[i,:])
    
    ani = matplotlib.animation.FuncAnimation(fig, update, frames=30, repeat=False)
    plt.show()
    

    我向new question 询问了为什么这不适用于 qt 后端。

    【讨论】:

      猜你喜欢
      • 2016-10-27
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 1970-01-01
      • 2020-03-24
      • 2017-05-28
      相关资源
      最近更新 更多