如何在python程序的简单UI中显示实时图形?

Nei*_*l G 18 python pyqt matplotlib vispy

我有一个复杂的算法,可以更新存储在数组中的3个直方图.我想调试我的算法,所以我想在用户界面中将数组显示为直方图.最简单的方法是什么?(快速应用程序开发比优化代码更重要.)

我有一些Qt(在C++中)的经验和matplotlib的一些经验.

(我将暂时搁置这个问题一两天,因为我很难在没有更多经验的情况下评估解决方案.希望社群的投票能帮助我们选择最佳答案.)

unu*_*tbu 21

编辑:现在,使用起来更容易,更好matplotlib.animation:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation


def animate(frameno):
    x = mu + sigma * np.random.randn(10000)
    n, _ = np.histogram(x, bins, normed=True)
    for rect, h in zip(patches, n):
        rect.set_height(h)
    return patches    

mu, sigma = 100, 15
fig, ax = plt.subplots()
x = mu + sigma * np.random.randn(10000)
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green', alpha=0.75)

ani = animation.FuncAnimation(fig, animate, blit=True, interval=10,
                              repeat=True)
plt.show()
Run Code Online (Sandbox Code Playgroud)

有制作一个动画图形的例子在这里.在此示例的基础上,您可以尝试以下方法:

import numpy as np
import matplotlib.pyplot as plt

plt.ion()
mu, sigma = 100, 15
fig = plt.figure()
x = mu + sigma*np.random.randn(10000)
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
for i in range(50):
    x = mu + sigma*np.random.randn(10000)
    n, bins = np.histogram(x, bins, normed=True)
    for rect,h in zip(patches,n):
        rect.set_height(h)
    fig.canvas.draw()
Run Code Online (Sandbox Code Playgroud)

我可以通过这种方式每秒获得大约14帧,而使用我首次发布的代码每秒可以获得4帧.诀窍是避免要求matplotlib绘制完整的数字.而是调用plt.hist一次,然后操纵现有的matplotlib.patches.Rectangles patches来更新直方图,并调用 fig.canvas.draw()以使更新可见.


Luk*_*uke 9

对于实时绘图,我建议尝试使用Chaco,pyqtgraph或任何基于opengl的库,如glumpy或visvis.Matplotlib虽然很棒,但通常不适合这种应用.

编辑: glumpy,visvis,galry和pyqtgraph的开发人员都在一个名为vispy的可视化库上进行协作.它仍然处于发展的早期阶段,但很有希望且已经相当强大.