如何在Python程序中为实时图表创建简单的UI?

20 投票
4 回答
39256 浏览
提问于 2025-04-16 06:46

我有一个复杂的算法,它会更新存储在数组中的三个直方图。我想调试这个算法,所以我在考虑在用户界面中把这些数组显示成直方图。有什么简单的方法可以做到这一点呢?(快速开发应用程序比优化代码更重要。)

我对Qt(用C++写的)有一些经验,也对matplotlib有一点了解。

(我打算把这个问题开放一两天,因为我没有足够的经验来评估解决方案。希望社区的投票能帮助我选择最佳答案。)

4 个回答

1

我建议在交互模式下使用matplotlib。如果你调用一次.show,它会在一个独立的窗口中弹出来。如果你不调用它,那么图形只会存在于内存中,等你完成后可以把它保存到文件里。

13

如果你想要实时绘图,我建议你试试 Chaco、pyqtgraph,或者一些基于 OpenGL 的库,比如 glumpy 或 visvis。虽然 Matplotlib 很棒,但一般来说不太适合这种应用。

补充:glumpy、visvis、galry 和 pyqtgraph 的开发者们正在合作开发一个叫做 vispy 的可视化库。这个库还在早期开发阶段,但前景不错,功能也已经相当强大。

23

编辑:现在使用 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()

这里有一个制作动画图表的例子,可以查看。在这个例子的基础上,你可以尝试类似的做法:

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

这样我大约能达到每秒14帧,而用我最初发布的代码时只能达到每秒4帧。关键是要避免让matplotlib重新绘制整个图形。相反,你可以先调用一次 plt.hist,然后对已经存在的 matplotlib.patches.Rectangle 进行操作,更新直方图,最后调用 fig.canvas.draw() 来让更新的内容显示出来。

撰写回答