我编写了一个用于模拟流行病演变的脚本(带有图表和散点图)。我尝试了几个库来实时显示结果(8 个国家 x 500 个粒子):
- Matplotlib(不够快)
- PyQtGraph(更好但仍然不够快)
- OpenGL(很好,但我没有找到如何在 2D 中有效地使用它,使用子图、标题、图例......)
- 散景(很好,但散点图每次变颜色时都会“闪烁”。如果您有兴趣,代码就在这里)
这就是我现在转向 VisPy 的原因。
我正在使用一个类Visualizer
来显示结果,并使用app.Timer().connect
管理实时端的方法。Pandemic
代码在这里。
from Pandemic import *
from vispy.plot import Fig
from vispy import app
class Visualizer:
def __init__(self, world):
self.fig = Fig()
self.world = world
self.traces = {}
#Scatter plots
for idx, c in world.countries.items():
pos_x = idx % self.world.nb_cols
pos_y = idx // self.world.nb_cols
subplot = self.fig[pos_y, pos_x]
data = np.array([c.x_coord, c.y_coord]).reshape(-1,2)
self.traces[idx] = subplot.plot(data, symbol='o', width=0, face_color=c.p_colors, title='Country {}'.format(idx+1))
def display(self):
for idx, c in self.world.countries.items():
data = np.array([c.x_coord, c.y_coord]).reshape(-1,2)
self.traces[idx].set_data(data, face_color=c.p_colors)
def update(self, event):
self.world.update(quarantine=False)
self.display()
def animation(self):
self.timer = app.Timer()
self.timer.connect(self.update)
self.timer.start(0)
self.start()
def start(self):
if (sys.flags.interactive != 1):
self.status = app.run()
if __name__ == '__main__':
w = World(move=0.001)
for i in range(8):
w.add_country(nb_S=500)
v = Visualizer(w)
v.animation()
与散景一样,每次粒子变色时,散点图都会“闪烁”。难道我做错了什么?
是否有更有效的实时显示方式,可能使用 vispy.gloo 或 vispy.scene?(目前它比 pyqtgraph.opengl 慢)