使用 pyqtgraph 有效地绘制大型数据集

2024-03-29

我正在尝试使用 pyqtgraph 生成散点图和直方图矩阵。每个散点图的输入(x 和 y 值)是长度大于 1,000,000 的 numpy 数组。生成这些图需要很长时间(2x2 绘图矩阵>1 分钟)(matplotlib 实际上生成相同图的速度更快)。你能指出我能做些什么来加快速度吗?下面是我正在使用的代码。

Thanks.

from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg

def scatter_matrix(data, cols):
    pg.setConfigOption('background', 'w')
    pg.setConfigOption('foreground', 'k')
    now = pg.ptime.time()

    app = QtGui.QApplication([])

    win = pg.GraphicsWindow(title="Scater Plot Matrix")
    win.resize(800,600)

    for i, col_i in enumerate(cols):
        for j, col_j in enumerate(cols):
            x = data[col_i]
            y = data[col_j]
            if i == j:
                current_plot = win.addPlot(title="Histogram")
                y,x = np.histogram(x, bins=100)
                curve = pg.PlotCurveItem(x, y, stepMode=True, fillLevel=0, brush=(0, 0, 255, 80))
                current_plot.addItem(curve)
            else:
                current_plot = win.addPlot(title="Scatter plot")
                current_plot.plot(x, y, pen=None, symbol='t', symbolPen=None, symbolSize=10, symbolBrush=(100, 100, 255, 50))
                current_plot.setLabel('left', "{}".format(col_i), units='')
                current_plot.setLabel('bottom', "{}".format(col_j), units='')
                current_plot.setLogMode(x=False, y=False)
        win.nextRow()
    ## Start Qt event loop unless running in interactive mode or using pyside.
    import sys
    print "Plot time: %0.2f sec" % (pg.ptime.time()-now)
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        app.exec_()

data = {}
for key in ['a','b']:
    data[key] = np.random.normal(size=(1000000), scale=1e-5)

scatter_matrix(data,['a','b'])

在网上进行了大量搜索后,我最终尝试了一个基于 GPU 的绘图库 galry。结果是速度提高了 100 倍以上!下面是代码。不管怎样,我仍然想知道是否有方法可以使用 pyqtgraph 加速绘图。

import numpy as np
from galry import *
import time

class MyPaintManager(PlotPaintManager):
    def initialize(self):
        if self.parent.visual == BarVisual:
            self.add_visual(self.parent.visual, self.parent.x, primitive_type= self.parent.plot_type, color='b')
        elif self.parent.visual == PlotVisual:
            self.add_visual(self.parent.visual, x=self.parent.x, y=self.parent.y, primitive_type= self.parent.plot_type, color='b')

class MyWidget(GalryWidget):
    def initialize(self, x, y, visual, title=None, plot_type=None):
        self.activate_grid = True
        self.show_grid = True

        self.x = x
        self.y = y
        self.visual = visual
        self.plot_type = plot_type
        self.title = title

        self.set_bindings(PlotBindings)
        self.set_companion_classes(
            paint_manager=MyPaintManager,
            interaction_manager=PlotInteractionManager,)
        self.initialize_companion_classes()

def scatter_matrix(df, cols):
    now = time.time()

    class Window(QtGui.QWidget):
        def __init__(self):
            super(Window, self).__init__()
            self.initUI()

        def initUI(self):
            vbox = QtGui.QGridLayout()
            self.setLayout(vbox)
            self.setGeometry(300, 300, 600, 600)
            for i, col_i in enumerate(cols):
                for j, col_j in enumerate(cols):
                    x = df[col_i]
                    y = df[col_j]
                    if i == j:
                        y,x = np.histogram(x, bins=100)
                        vbox.addWidget(MyWidget(x=y,y=y, visual = BarVisual, title='{}_vs_{}'.format(col_i, col_j)), i, j)
                    else:
                        vbox.addWidget(MyWidget(x=x,y=y, visual = PlotVisual, title='{}_vs_{}'.format(col_i, col_j), plot_type='POINTS'), i, j)

            print "Plot time: %0.2f sec" % (time.time()-now)
            self.show()

    show_window(Window)

if __name__ == '__main__':
    data = {}
    for key in ['a','b']:
        data[key] = np.random.normal(size=(1000000), scale=1e-5)

    scatter_matrix(data,['a','b'])

你的代码看起来不错。根据您的系统,pyqtgraph 的散点图效率会降低约 10k 到 100k 点。如果您确实想继续使用 pyqtgraph,我可以建议的是将您的数据进行 10 倍到 100 倍的子采样。

您想要可视化的数据量几乎需要 GPU 加速,因此 Galry 是一个很好的工具。仅供参考,pyqtgraph、Galry 和其他一些 python 图形库的开发人员正在 VisPy 上进行合作,虽然还没有完全准备好使用,但将来应该是一个非常好的选择。 PyQtGraph 未来还将使用 VisPy 提供 GPU 加速。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 pyqtgraph 有效地绘制大型数据集 的相关文章

随机推荐