【问题标题】:time-depending layout of graph in pyqtgraphpyqtgraph中图形的时间依赖布局
【发布时间】:2016-09-24 11:21:39
【问题描述】:

一天的好时光!我正在尝试使用pyqtgraph 制作带有时间绘图的树形图,并且在 pyqtgraph 示例中仅找到了CustomGraphItemQTimer 中的教程。我找不到如何使顶点和边布局取决于时间的方法。我需要在几秒钟的时间间隔内将它们布置好。你能给我一些代码或建议如何做到这一点吗?我的代码与示例非常相似:

# -*- coding: utf-8 -*-

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

# Enable antialiasing for prettier plots
pg.setConfigOptions(antialias=True)

w = pg.GraphicsWindow()
w.setWindowTitle('pyqtgraph example: CustomGraphItem')
v = w.addViewBox()
v.setAspectLocked()


class Graph(pg.GraphItem):
    def __init__(self):
        self.dragPoint = None
        self.dragOffset = None
        self.textItems = []
        pg.GraphItem.__init__(self)
        self.scatter.sigClicked.connect(self.clicked)

    def setData(self, **kwds):
        self.text = kwds.pop('text', [])
        self.data = kwds
        if 'pos' in self.data:
            npts = self.data['pos'].shape[0]
            self.data['data'] = np.empty(npts, dtype=[('index', int)])
            self.data['data']['index'] = np.arange(npts)
        self.setTexts(self.text)
        self.updateGraph()

    def setTexts(self, text):
        for i in self.textItems:
            i.scene().removeItem(i)
        self.textItems = []
        for t in text:
            item = pg.TextItem(t)
            self.textItems.append(item)
            item.setParentItem(self)

    def updateGraph(self):
        pg.GraphItem.setData(self, **self.data)
        for i, item in enumerate(self.textItems):
            item.setPos(*self.data['pos'][i])

    def mouseDragEvent(self, ev):
        if ev.button() != QtCore.Qt.LeftButton:
            ev.ignore()
            return

        if ev.isStart():
            # We are already one step into the drag.
            # Find the point(s) at the mouse cursor when the button was first
            # pressed:
            pos = ev.buttonDownPos()
            pts = self.scatter.pointsAt(pos)
            if len(pts) == 0:
                ev.ignore()
                return
            self.dragPoint = pts[0]
            ind = pts[0].data()[0]
            self.dragOffset = self.data['pos'][ind] - pos
        elif ev.isFinish():
            self.dragPoint = None
            return
        else:
            if self.dragPoint is None:
                ev.ignore()
                return

        ind = self.dragPoint.data()[0]
        self.data['pos'][ind] = ev.pos() + self.dragOffset
        self.updateGraph()
        ev.accept()

    def clicked(self, pts):
        print("clicked: %s" % pts)


g = Graph()
v.addItem(g)

## Define positions of nodes
pos = np.array([
    [5, 10],
    [3, 8],
    [8, 8],
    [10, 10],
    [-5, 0],
    [6, 5],
], dtype=float)



## Define the set of connections in the graph
adj = np.array([
    [0, 1],
    [1, 3],
    [3, 0],
    [2, 0],
    [1, 5],
    [1, 5],
    [5, 4],
])


## Define the symbol to use for each node (this is optional)
symbols = ['o', 'o', 'o', 'o', 't', '+']


## Define the line style for each connection (this is optional)
lines = np.array([
    (255, 0, 0, 255, 1),
    (255, 0, 255, 255, 2),
    (255, 0, 255, 255, 3),
    (255, 255, 0, 255, 2),
    (255, 0, 0, 255, 1),
    (255, 255, 255, 255, 8),
    (200, 235, 150, 255, 4),
], dtype=[('red', np.ubyte), ('green', np.ubyte), ('blue', np.ubyte), ('alpha', np.ubyte), ('width', float)])


## Define text to show next to each symbol
texts = ["Point %d" % i for i in range(6)]

## Update the graph
g.setData(pos=pos, adj=adj, pen=lines, size=1, symbol=symbols, pxMode=False, text=texts)


timer = pg.QtCore.QTimer()
def update():
    g.plot(x, y, clear=True)
timer.timeout.connect(update)
timer.start(16)


## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    import sys

    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

【问题讨论】:

    标签: python animation pyqtgraph


    【解决方案1】:

    因为没有答案,所以我添加 - 我确实以以下形式修复:

    # -*- coding: utf-8 -*-
    
    import pyqtgraph as pg
    from pyqtgraph.Qt import QtCore, QtGui
    import numpy as np
    import random
    
    # Enable antialiasing for prettier plots
    pg.setConfigOptions(antialias=True)
    
    w = pg.GraphicsWindow()
    w.setWindowTitle('pyqtgraph example: CustomGraphItem')
    v = w.addViewBox()
    v.setAspectLocked()
    
    
    class Graph(pg.GraphItem):
        def __init__(self):
            self.dragPoint = None
            self.dragOffset = None
            self.textItems = []
            pg.GraphItem.__init__(self)
            self.scatter.sigClicked.connect(self.clicked)
    
        def setData(self, **kwds):
            self.text = kwds.pop('text', [])
            self.data = kwds
            if 'pos' in self.data:
                npts = self.data['pos'].shape[0]
                self.data['data'] = np.empty(npts, dtype=[('index', int)])
                self.data['data']['index'] = np.arange(npts)
            self.setTexts(self.text)
            self.updateGraph()
    
        def setTexts(self, text):
            for i in self.textItems:
                i.scene().removeItem(i)
            self.textItems = []
            for t in text:
                item = pg.TextItem(t)
                self.textItems.append(item)
                item.setParentItem(self)
    
        def updateGraph(self):
            pg.GraphItem.setData(self, **self.data)
            for i, item in enumerate(self.textItems):
                item.setPos(*self.data['pos'][i])
    
        def mouseDragEvent(self, ev):
            if ev.button() != QtCore.Qt.LeftButton:
                ev.ignore()
                return
    
            if ev.isStart():
                # We are already one step into the drag.
                # Find the point(s) at the mouse cursor when the button was first
                # pressed:
                pos = ev.buttonDownPos()
                pts = self.scatter.pointsAt(pos)
                if len(pts) == 0:
                    ev.ignore()
                    return
                self.dragPoint = pts[0]
                ind = pts[0].data()[0]
                self.dragOffset = self.data['pos'][ind] - pos
            elif ev.isFinish():
                self.dragPoint = None
                return
            else:
                if self.dragPoint is None:
                    ev.ignore()
                    return
    
            ind = self.dragPoint.data()[0]
            self.data['pos'][ind] = ev.pos() + self.dragOffset
            self.updateGraph()
            ev.accept()
    
        def clicked(self, pts):
            print("clicked: %s" % pts)
    
    
    g = Graph()
    v.addItem(g)
    
    pos = np.array([]).reshape(0, 2)
    adj = np.array([]).reshape(0, 2)
    symbols = []
    symbols2 = []
    
    
    data_adj= np.array([
        [2, 4],
        [2, 0],
        [1, 3],
        [3, 0],
        [1, 0],
        [1, 5]
    ])
    
    zero_lines = np.array([
        (0, 0, 0, 255, 1),
        (0, 0, 0, 255, 2),
        (0, 0, 0, 255, 3),
        (0, 0, 0, 255, 2),
        (0, 0, 0, 255, 1),
        (0, 0, 0, 255, 8),
    ], dtype=[('red', np.ubyte), ('green', np.ubyte), ('blue', np.ubyte), ('alpha', np.ubyte), ('width', float)])
    
    color_lines = np.array([
        (255, 0, 0, 255, 5),
        (0, 255, 0, 255, 1),
        (0, 0, 255, 255, 2),
        (255, 0, 0, 255, 3),
    ], dtype=[('red', np.ubyte), ('green', np.ubyte), ('blue', np.ubyte), ('alpha', np.ubyte), ('width', float)])
    
    
    data_pos = np.array([
        [5, 10],
        [3, 8],
        [8, 8],
        [10, 10],
        [-5, 0],
        [6, 5],
    ], dtype=float)
    
    data_texts = ["Point %d" % i for i in range(6)]
    
    data_symbols = ['o', 'o', 'o', 'o', 't', '+']
    
    
    def update():
        global data_pos, data_adj, zero_lines, color_lines
        zero_lines = np.delete(zero_lines, 0, 0)
    
        zero_lines = np.append(zero_lines, color_lines[random.randint(0, len(color_lines) - 1)])
    
        g.setData(pos=data_pos, adj=data_adj, pen=zero_lines, size=1, symbol=data_symbols, pxMode=False, text=data_texts)
    
    
    
    
    timer = QtCore.QTimer()
    timer.timeout.connect(update)
    timer.start(1000)
    
    # Start Qt event loop unless running in interactive mode or using pyside.
    if __name__ == '__main__':
        import sys
    
        if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
            QtGui.QApplication.instance().exec_()
    

    也许这对决定在 pyqtgraph 中制作图形动画的人会有所帮助

    【讨论】:

      猜你喜欢
      • 2016-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 2013-02-10
      • 1970-01-01
      • 2012-02-24
      • 1970-01-01
      相关资源
      最近更新 更多