Cheap way to color lots of segments of a PlotDataItem?

110 views
Skip to first unread message

Preston Hinkle

unread,
Aug 23, 2016, 2:14:11 PM8/23/16
to pyqtgraph
Hello,

As the title suggests, I'm looking for a way to change the color of discrete segments of a PlotDataItem. My current method creates a PlotDataItem for every segment and plots it over the background with a different pen, but this is apparently very expensive when the number of segments accumulates to around a 1000. Instead, is it possible to draw segments of a single PlotDataItem with different pens? I looked through the documentation but couldn't find anything.

Thanks!

Luke Campagnola

unread,
Aug 27, 2016, 3:02:42 AM8/27/16
to pyqt...@googlegroups.com
PyQtGraph doesn't provide anything like this, but it's pretty easy to write as a QGraphicsItem class. As long as you don't need the data to update rapidly, you can "bake" all of your line segments into a single QPicture. This should be very quick to redraw:

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

class Segments(QtGui.QGraphicsItem):
    def __init__(self, pos, color):
        QtGui.QGraphicsItem.__init__(self)
        self.pic = QtGui.QPicture()
        painter = QtGui.QPainter()
        painter.begin(self.pic)
        for i in range(len(pos)-1):
            painter.setPen(QtGui.QPen(QtGui.QColor(*color[i])))
            p1 = QtCore.QPointF(*pos[i])
            p2 = QtCore.QPointF(*pos[i+1])
            painter.drawLine(p1, p2)
        painter.end()

    def paint(self, p, *args):
        p.drawPicture(0, 0, self.pic)

    def boundingRect(self):
        return QtCore.QRectF(self.pic.boundingRect())


pos = np.empty((10000,2))
pos[:,0] = np.linspace(0, 10, 10000)
pos[:,1] = np.random.normal(size=(10000))

color = np.random.random(size=(9999,3)) * 255

p = pg.plot()
seg = Segments(pos, color)
p.addItem(seg)


--
You received this message because you are subscribed to the Google Groups "pyqtgraph" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pyqtgraph+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/pyqtgraph/69a62e28-d917-459b-bdee-699a426e61df%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Preston Hinkle

unread,
Aug 30, 2016, 9:55:36 AM8/30/16
to pyqtgraph
Great, I'll try to implement it.

Thanks! Really loving pyqtgraph btw.
To unsubscribe from this group and stop receiving emails from it, send an email to pyqtgraph+...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages