gpt4 book ai didi

python - 如何使用 VisPy 库实时绘图?

转载 作者:行者123 更新时间:2023-12-04 04:13:37 25 4
gpt4 key购买 nike

我编写了一个脚本来模拟流行病的演变(带有图表和散点图)。我尝试了几个库来实时显示结果(8 个国家 x 500 个粒子):

  • Matplotlib(不够快)
  • PyQtGraph(更好但仍然不够快)
  • OpenGL(很好,但我没有找到如何有效地在 2D 中使用它,使用子图、标题、图例...)
  • Bokeh (很好,但散点图在每次粒子变色时“闪烁”。代码是 here 如果您有兴趣)

这就是我现在转向 VisPy 的原因。

我正在使用类 Visualizer 来显示结果,使用方法 app.Timer().connect 来管理实时端。 Pandemic 代码是 here .

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

每当散点图的粒子变色时,散点图就会“闪烁”,就像 Bokeh 一样。难道我做错了什么?

是否有更有效的实时显示方式,也许使用 vispy.gloo 或 vispy.scene? (目前比pyqtgraph.opengl慢)

最佳答案

我们可以通过使用 vispy.gloo 模块来有效地实时绘图,以利用 GPU 的强大功能。这是一种方法:

1) 构建继承vispy.app.Canvas类的类。

2) 创建一个输入为着色器的 OpenGL 程序。该对象允许我们将数据链接到着色器变量。 Canvas 上的每个点都取决于这些变量值(描述其坐标、颜色等)。例如,显示文本(标题、标签等)比使用 Matplotlib 库要难得多。 Here是对该过程的更深入解释。

3) 设置一个计时器连接到我们要重复调用的函数(实时端)。

vispy.scene 模块专用于科学家的高级可视化界面,仍处于试验阶段。也许这就是为什么我的第一个代码出现一些错误的原因。

Here是我的新代码。

关于python - 如何使用 VisPy 库实时绘图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61212937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com