pyqtgraph LinearRegionItem get curve data between selected region - python

I am new to pyqtGraph and using LinearRegionItem for selection. Is there a way i can get data for curves only for selection ?
For me getting data which lies between selection is important to process.
Any help of pointer in right direction will be helpful
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg
#
app = QtGui.QApplication([])
#
win = pg.GraphicsWindow()
win.resize(1000, 600)
#
p1 = win.addPlot(title="Multiple curves")
p1.plot(np.random.normal(size=100), pen=(255, 0, 0), name="Red curve")
p1.plot(np.random.normal(size=110) + 5, pen=(0, 255, 0), name="Blue curve")
# LinearRegionItem
#
def updateRegion(window, viewRange):
region = lr.getRegion()
print region
#
lr = pg.LinearRegionItem([10, 40])
lr.setZValue(-10)
p1.addItem(lr)
p1.sigXRangeChanged.connect(updateRegion)
#
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()

Pyqtgraphs linearregionitem has a signal called sigRegionChanged.
With this signal the regionItem emits itself when the user drags it or when it is changed programatically. Using getRegion() you can then get the low and high of the linearregionitem.
def regionUpdated(regionItem):
lo,hi = regionItem.getRegion()
print lo,hi
lr.sigRegionChanged.connect(regionUpdated)
This will output the position low and high when dragged, e.g.
9.50787175868 13.9172032101
If you have your red curve as a numpy array then you can slice it using the lo and hi.
red = np.random.normal(size=100)
red[9.50787175868:13.9172032101]
Which gives
[ 0.13231953 -0.5609786 -0.13632821 0.79973 ]
Slicing an index array with floats can feel a bit weird, but numpy runs int() on the indices first, basically making the call red[9:13]. See the question "Why ndarray allow floating point index?" for more about this.
The slicing can be done in regionUpdated and then you can do anything you want with the slice, e.g. print it!
def regionUpdated(regionItem):
lo,hi = regionItem.getRegion()
print red[lo:hi]

Related

How do the scaling paramters of ViewBox.setLimits() work?

I'm trying to limit how much a ViewBox can zoom in/out and how much it can be moved.
I know that I must use setLimits() and I've read the documentation here
https://pyqtgraph.readthedocs.io/en/latest/graphicsItems/viewbox.html#pyqtgraph.ViewBox.setLimits
While the panning limits are pretty self evident, I can't really understand how the scaling limits work.
What's the unit of measure? Is it pixels? Percentage?
I've reached a usable point with these values, but not understanding why is bugging me!
view.setLimits(xMin=-image.shape[0]*0.05, xMax=image.shape[0]*1.05,
minXRange=100, maxXRange=2000,
yMin=-image.shape[1]*0.05, yMax=image.shape[1]*1.05,
minYRange=100, maxYRange=2000)
I think it's a more theoretical question than anything else, but in case you want to try some code, here it is
# import the necessary packages
from pyqtgraph.graphicsItems.ImageItem import ImageItem
from pyqtgraph.graphicsItems.LinearRegionItem import LinearRegionItem
import requests
import numpy as np
import cv2
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
image = cv2.imread('aggraffatura.jpg') # Change the picture here!
image = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)
app = QtGui.QApplication([])
## Create window with GraphicsView widget
w = pg.GraphicsView()
w.show()
w.resize(image.shape[0]/2, image.shape[1]/2) # Depending on the picture you may not need to resize
w.setWindowTitle('Test')
view = pg.ViewBox()
view.setLimits(xMin=-image.shape[0]*0.05, xMax=image.shape[0]*1.05,
minXRange=100, maxXRange=2000,
yMin=-image.shape[1]*0.05, yMax=image.shape[1]*1.05,
minYRange=100, maxYRange=2000)
w.setCentralItem(view)
## lock the aspect ratio
view.setAspectLocked(True)
## Add image item
item = ImageItem(image)
view.addItem(item)
## Add line item
line = LinearRegionItem()
view.addItem(line)
def mouseClicked(evt):
pos = evt[0]
print(pos)
proxyClicked = pg.SignalProxy(w.scene().sigMouseClicked, rateLimit=60, slot=mouseClicked)
## Start Qt event loop unless running in interactive mode.
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
What's the unit of measure? Is it pixels? Percentage?
Short answer: The unit of measure of scaling limits is the same as the panning limits.
Long answer:
In class ViewBox, method setLimits calls method updateViewRange, which update view range to match the target view range as closely as possible, given aspect ratio constraints. Inside updateViewRange method, there is a section which loop through both axis and set the max view range to the smaller of max view range (the max scaling limit) and the absolute difference of lower and upper bounds (i.e. max-min, the difference of panning limits) (If scaling limit is not given, than it will be set to the difference of panning limits). Since the two limits can be interchangeable, they should have the same unit of measure.
Only by checking the source code one can see that max range cannot be larger than bounds, if they are given. This piece of information should be added to the document.
Note: when you zoom in to the limit you are actually setting the view range to the minRange of scaling limit.
Example: Here I will use op's example to illustrate the concept. Download this image and rename it to '500x500' to test the example.. On start you should see that the view range is set to maxRange(400px) which is the diameter of the green circle. By zooming in, you should see that the view range can never be smaller than the red circle, which is 100px in diameter. The panning limit is set to the shape of the image, i.e. 500 X 500px.
# import the necessary packages
from pyqtgraph.graphicsItems.ImageItem import ImageItem
from pyqtgraph.graphicsItems.LinearRegionItem import LinearRegionItem
import requests
import numpy as np
import cv2
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
# Name the image to 500x500
image = cv2.imread('500x500.jpg') # Change the picture here!
image = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)
app = QtGui.QApplication([])
## Create window with GraphicsView widget
w = pg.GraphicsView()
w.show()
w.resize(image.shape[0], image.shape[1]) # Depending on the picture you may not need to resize
w.setWindowTitle('Test')
view = pg.ViewBox()
view.setLimits(xMin=0, xMax=image.shape[0],
minXRange=100, maxXRange=400,
yMin=0, yMax=image.shape[1],
minYRange=100, maxYRange=400)
w.setCentralItem(view)
## lock the aspect ratio
view.setAspectLocked(True)
## Add image item
item = ImageItem(image)
view.addItem(item)
## Add line item
line = LinearRegionItem()
view.addItem(line)
def mouseClicked(evt):
pos = evt[0]
print(pos)
proxyClicked = pg.SignalProxy(w.scene().sigMouseClicked, rateLimit=60, slot=mouseClicked)
## Start Qt event loop unless running in interactive mode.
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()

How to update a plot in pyqtgraph?

I am trying to have a user interface using PyQt5 and pyqtgraph. I made two checkboxes and whenever I select them I want to plot one of the two data sets available in the code and whenever I deselect a button I want it to clear the corresponding curve. There are two checkboxes with texts A1 and A2 and each of them plot one set of data.
I have two issues:
1- If I select A1 it plots the data associated with A1 and as long as I do not select A2, by deselecting A1 I can clear the data associated with A1.
However, If I check A1 box and then I check A2 box, then deselecting A1 does not clear the associated plot. In this situation, if I choose to plot random data, instead of a deterministic curve such as sin, I see that by selecting either button new data is added but it cannot be removed.
2- The real application have 96 buttons each of which should be associated to one data set. I think the way I wrote the code is inefficient because I need to copy the same code for one button and data set 96 times. Is there a way to generalize the toy code I presented below to arbitrary number of checkboxes? Or perhaps, using/copying the almost the same code for every button is the usual and correct way to do this?
The code is:
from PyQt5 import QtWidgets, uic, QtGui
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector
import numpy as np
import sys
import string
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
app = QtWidgets.QApplication(sys.argv)
x = np.linspace(0, 3.14, 100)
y1 = np.sin(x)#Data number 1 associated to checkbox A1
y2 = np.cos(x)#Data number 2 associated to checkbox A2
#This function is called whenever the state of checkboxes changes
def todo():
if cbx1.isChecked():
global curve1
curve1 = plot.plot(x, y1, pen = 'r')
else:
try:
plot.removeItem(curve1)
except NameError:
pass
if cbx2.isChecked():
global curve2
curve2 = plot.plot(x, y2, pen = 'y')
else:
try:
plot.removeItem(curve2)
except NameError:
pass
#A widget to hold all of my future widgets
widget_holder = QtGui.QWidget()
#Checkboxes named A1 and A2
cbx1 = QtWidgets.QCheckBox()
cbx1.setText('A1')
cbx1.stateChanged.connect(todo)
cbx2 = QtWidgets.QCheckBox()
cbx2.setText('A2')
cbx2.stateChanged.connect(todo)
#Making a pyqtgraph plot widget
plot = pg.PlotWidget()
#Setting the layout
layout = QtGui.QGridLayout()
widget_holder.setLayout(layout)
#Adding the widgets to the layout
layout.addWidget(cbx1, 0,0)
layout.addWidget(cbx2, 0, 1)
layout.addWidget(plot, 1,0, 3,1)
widget_holder.adjustSize()
widget_holder.show()
sys.exit(app.exec_())
Below is an example I made that works fine.
It can be reused to do more plots without increasing the code, just changing the value of self.num and adding the corresponding data using the function add_data(x,y,ind), where x and y are the values of the data and ind is the index of the box (from 0 to n-1).
import sys
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
class MyApp(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.central_layout = QtGui.QVBoxLayout()
self.plot_boxes_layout = QtGui.QHBoxLayout()
self.boxes_layout = QtGui.QVBoxLayout()
self.setLayout(self.central_layout)
# Lets create some widgets inside
self.label = QtGui.QLabel('Plots and Checkbox bellow:')
# Here is the plot widget from pyqtgraph
self.plot_widget = pg.PlotWidget()
# Now the Check Boxes (lets make 3 of them)
self.num = 6
self.check_boxes = [QtGui.QCheckBox(f"Box {i+1}") for i in range(self.num)]
# Here will be the data of the plot
self.plot_data = [None for _ in range(self.num)]
# Now we build the entire GUI
self.central_layout.addWidget(self.label)
self.central_layout.addLayout(self.plot_boxes_layout)
self.plot_boxes_layout.addWidget(self.plot_widget)
self.plot_boxes_layout.addLayout(self.boxes_layout)
for i in range(self.num):
self.boxes_layout.addWidget(self.check_boxes[i])
# This will conect each box to the same action
self.check_boxes[i].stateChanged.connect(self.box_changed)
# For optimization let's create a list with the states of the boxes
self.state = [False for _ in range(self.num)]
# Make a list to save the data of each box
self.box_data = [[[0], [0]] for _ in range(self.num)]
x = np.linspace(0, 3.14, 100)
self.add_data(x, np.sin(x), 0)
self.add_data(x, np.cos(x), 1)
self.add_data(x, np.sin(x)+np.cos(x), 2)
self.add_data(x, np.sin(x)**2, 3)
self.add_data(x, np.cos(x)**2, 4)
self.add_data(x, x*0.2, 5)
def add_data(self, x, y, ind):
self.box_data[ind] = [x, y]
if self.plot_data[ind] is not None:
self.plot_data[ind].setData(x, y)
def box_changed(self):
for i in range(self.num):
if self.check_boxes[i].isChecked() != self.state[i]:
self.state[i] = self.check_boxes[i].isChecked()
if self.state[i]:
if self.plot_data[i] is not None:
self.plot_widget.addItem(self.plot_data[i])
else:
self.plot_data[i] = self.plot_widget.plot(*self.box_data[i])
else:
self.plot_widget.removeItem(self.plot_data[i])
break
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
Note that inside de PlotWidget I add the plot using the plot() method, it returns a PlotDataItem that is saved in the list created before called self.plot_data.
With this, you can easily remove it from the Plot Widget and add it again. Also if you are aiming for a more complex program, for example, one that you can change the data of each box on the run, the plot will update without major issues if you use the setData() method on the PlotDataItem
As I said at the beginning, this should work fine with a lot of checkboxes, because the function that is called when a checkbox is Checked/Unchecked, first compare the actual state of each box with the previous one (stored in self.state) and only do the changes on the plot corresponding to that specific box. With this, you avoid doing one function for each checkbox and the replot of all de boxes every time you check/uncheck a box (like user8408080 did). I don't say it is bad, but if you increase the number of checkboxes and/or the complexity of the data, the workload of replotting all of the data will increase drastically.
The only problem will be when the window is too small to support a crazy amount of checkboxes (96 for example), then you will have to organize the checkboxes in another widget instead of a layout.
Now some screenshots of the code from above:
And then changing the value of self.num to 6 and adding some random data to them:
self.add_data(x, np.sin(x)**2, 3)
self.add_data(x, np.cos(x)**2, 4)
self.add_data(x, x*0.2, 5)
In the following I take a more brute force approach, while assuming, that plotting all the curves takes an negligible amount of time:
import numpy as np
import sys
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtWidgets
app = QtWidgets.QApplication(sys.argv)
x = np.linspace(0, 3.14, 100)
y1 = np.sin(x)#Data number 1 associated to checkbox A1
y2 = np.cos(x)#Data number 2 associated to checkbox A2
curves = [y1, y2]
pens = ["r", "y"]
#This function is called whenever the state of checkboxes changes
def plot_curves(state):
plot.clear()
for checkbox, curve, pen in zip(checkboxes, curves, pens):
if checkbox.isChecked():
plot.plot(x, curve, pen=pen)
#A widget to hold all of my future widgets
widget_holder = QtGui.QWidget()
#Making a pyqtgraph plot widget
plot = pg.PlotWidget()
#Setting the layout
layout = QtGui.QGridLayout()
widget_holder.setLayout(layout)
checkboxes = [QtWidgets.QCheckBox() for i in range(2)]
for i, checkbox in enumerate(checkboxes):
checkbox.setText(f"A{i+1}")
checkbox.stateChanged.connect(plot_curves)
layout.addWidget(checkbox, 0, i)
#Adding the widgets to the layout
layout.addWidget(plot, 1, 0, len(checkboxes), 0)
widget_holder.adjustSize()
widget_holder.show()
sys.exit(app.exec_())
Now you have a list of checkboxes and the checkbox with index 0 corresponds to the data in the curves-list with index 0. I plot all the curves everytime, which yields a little bit more readable code. If this does affect performance, though, this needs to be a little more complicated.
I also tried to add another curve and it seems to work out perfectly fine:
I found the problem in your code. Let's see what your code does:
When you add the first plot to the widget (either A1 or A2) you get the PlotDataItem and store it in curve1 or curve2. Suppose you check first A1, then your todo function first inspects that the checkbox 1 is Checked, so plot the data and store it in curve1, then the same function inspects the checkbox 2. Checkbox 2 is not checked so the function does the else statement, which removes the curve2 from the plot widget, this variable doesn't exist so it might raise an error, however, you use the try statement and the error never raises.
Now, you check the A2 box, your function first inspects checkbox 1, it is checked, so the function will add again the same plot, but as another PlotDataItem, and store it in curve1. Until now, you have two PlotDataItem of the same data (that means two plots) but only the last one is stored in curve1. The next thing the function does is inspect checkbox 2, it is checked so it will plot the second data and save its PlotDataItem in curve2
So, when you now uncheck checkbox 1, your function first inspects checkbox 1 (sorry if it is repetitive), it is unchecked, so the function will remove the PlotDataItem stored in curve1 and it does it, but remember you have two plots of the same data, so for us (the viewers) the plot doesn't disappear. That is the problem, but it doesn't end there, the function now inspects checkbox 2, it is checked, so the function will add another PlotDataItem of the second data and stores it in curve2. We again will have the same problem that happened to the first data.
With this analysis, I also learned something, the PlotDataItem doesn´t disappear if you "overwrite" the variable in which it is stored, neither it does when it is removed from the PlotWidget. Considering that, I did some changes to the code of my previous answer because the old code will create another item each time we check a box that was checked before and was unchecked. Now, if the item is created, my function will add it again, instead of creating another one.
I have some suggestions:
Try using objects, generate your own widget class. You can avoid calling global variables, passing them as attributes of the class. (Like my previous answer)
If you want to maintain your code as it is (without the use of classes), for it to work, you can add another two variables with the "state" of your checkboxes, so when you call your function first it checks if the state didn´t change and ignore that checkbox. Also, check if the PlotDataItem was generated before and only add it again to avoid the generation of more items.
Your objective is to do this with a bunch of boxes or buttons, try using only one variable for all of them: for example, a list, containing all of the boxes/buttons (the objects). Then you can manage any of them by the index. Also, you can do loops over that variable for connecting the objects inside to the same function.
my_buttons = [ QtGui.QPushButton() for _ in range(number_of_buttons) ]
my_boxes= [ QtGui.QCheckBox() for _ in range(number_of_boxes) ]
my_boxes[0].setText('Box 1 Here')
my_boxes[2].setChecked(True)
for i in range(number_of_boxes):
my_boxes[i].stateChanged.connect(some_function)
Doing lists of objects also helps you to give names automatically easily:
my_boxes= [ QtGui.QCheckBox(f"Box number {i+1}") for i in range(number_of_boxes) ]
my_boxes= [ QtGui.QCheckBox(str(i+1)) for i in range(number_of_boxes) ]
my_boxes= [ QtGui.QCheckBox('Box {:d}'.format(i+1)) for i in range(number_of_boxes) ]
Finally, here is your code with some small changes to make it work:
from PyQt5 import QtWidgets, uic, QtGui
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector
import numpy as np
import sys
import string
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
app = QtWidgets.QApplication(sys.argv)
x = np.linspace(0, 3.14, 100)
y1 = np.sin(x)#Data number 1 associated to checkbox A1
y2 = np.cos(x)#Data number 2 associated to checkbox A2
#This function is called whenever the state of checkboxes changes
def todo():
global b1st, b2st, curve1, curve2
if cbx1.isChecked() != b1st:
b1st = cbx1.isChecked()
if cbx1.isChecked():
if curve1 is None:
curve1 = plot.plot(x, y1, pen = 'r')
else:
plot.addItem(curve1)
else:
plot.removeItem(curve1)
if cbx2.isChecked() != b2st:
b2st = cbx2.isChecked()
if cbx2.isChecked():
if curve2 is None:
curve2 = plot.plot(x, y2, pen = 'y')
else:
plot.addItem(curve2)
else:
plot.removeItem(curve2)
#A widget to hold all of my future widgets
widget_holder = QtGui.QWidget()
#Checkboxes named A1 and A2
cbx1 = QtWidgets.QCheckBox()
cbx1.setText('A1')
cbx1.stateChanged.connect(todo)
b1st = False
curve1 = None
cbx2 = QtWidgets.QCheckBox()
cbx2.setText('A2')
cbx2.stateChanged.connect(todo)
b2st = False
curve2 = None
#Making a pyqtgraph plot widget
plot = pg.PlotWidget()
#Setting the layout
layout = QtGui.QGridLayout()
widget_holder.setLayout(layout)
#Adding the widgets to the layout
layout.addWidget(cbx1, 0,0)
layout.addWidget(cbx2, 0, 1)
layout.addWidget(plot, 1,0, 3,1)
widget_holder.adjustSize()
widget_holder.show()
sys.exit(app.exec_())

Draw Hexahedral Mesh Efficiently Using OpenGL

I try to implement some kind of mesh visualiser for Finite-Element-Programms in Python. For this, I want to use PyQtGraph. I was able to implement a first version of the Visualiser which is able to plot a 3D mesh as shown in the picture below.
However, operations such as zooming and rotating take quite long for larger meshes. I plot the mesh using GLLinePlotItem. I guess the performance is poor due to the huge amount of lines generated with large meshes.
I am wondering whether there is an efficient way to display my mesh rather than using the GLLineItem. I had a look at GLMeshItem, however, this represents the mesh using triangles and not quads.
Here is my code for the visualiser:
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.opengl as gl
import pyqtgraph as pg
import numpy as np
import sys
class Visualizer(object):
def __init__(self):
self.app = QtGui.QApplication(sys.argv)
self.w = gl.GLViewWidget()
self.w.opts['distance'] = 400
self.w.setWindowTitle('Mesh Visualiser')
self.w.setGeometry(0, 110, 1920, 1080)
self.w.show()
def start(self):
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
def add_line_item(self,pts,width):
item = gl.GLLinePlotItem(pos=pts, width=width, antialias=False)
self.w.addItem(item)
if __name__ == '__main__':
v = Visualizer()
# Code which generates the GlLineItems is called here ...
# ...
v.start()
I also have a code which is called at the position of the comment in the code and generates the GlLinePlotItems from the nodes of the mesh. The GlLinePlotItems are added to the GlViewWidget using the `add_line_item() method.

corner coordinates of rectangular pyqtgraph roi

Suppose you have a rectangular pyqtgraph roi instance with some data:
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
data = np.random.random(size=(50,50,50))
app = QtGui.QApplication([])
w = pg.ImageView()
roi = pg.RectROI([20, 20], [20, 20], pen=(0,9))
roi.addRotateHandle([1, 0], [0.5, 0.5])
w.setImage(data)
w.addItem(roi)
w.show()
How can I extract the 4 corner coordinates of the roi after scaling/rotating it? It think it is possible to calculate them trigonometrically after calling
pos_x, pos_y = roi.pos()
angle = roi.angle()
size_x, size_y = roi.size()
However, it is not that straight forward since the angle can take values >360° etc. I feel like I have missed some build-in solution.
smiet
i am looking for something similar, but after looking into the documentation, source code and web, i think you are indeed left with your trigonometrical solution. nevertheless you could save two lines of code by calling
roi.getState()
which holds your wanted information in a dictionary.
regarding your problem with angles over 360° - shouldn't the modulo operator do the trick?
angle = 365 % 360
..or did i get your problem wrong?

How do I update graph fast with PyQtGraph and ScatterPlotItem (>1 fps)?

Hi all PyQtGraph users,
I am trying to use Matplotlibs jet colors in the pg.ScatterPlotItem for real-time graph update using data from a datalogger. I convert jet colors to RGBA code in the following few lines:
z=np.random.randint(0,10000,10000) #random z value
norm = mpl.colors.Normalize(vmin=min(z), vmax=max(z))
m = cm.ScalarMappable(norm=norm, cmap=cm.jet)
colors = m.to_rgba(z, bytes=True)
I have noticed that the speed in the scatterplot update can be an issue if the number of points is 10k or higher. For instance, on my laptop I get an update speed of 0.16 fps for 10k points if I run example code from the ScatterplotTestSpeed.py. However, if I append lists as tuples I can triple the update speed to 0.45 fps:
colors_=[]
for i in colors:
colors_.append(pg.mkBrush(tuple(i)))
This is a small trick I discovered by simple try and see method, but I was wondering if there are more of such tricks to speed up the fps number?!
Here is my entire code to test the update speed. It is heavily based on the ScatterPlotSpeedTest.py form the pyqtgraphs example library. Any help is appreciated :-)
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
For testing rapid updates of ScatterPlotItem under various conditions.
(Scatter plots are still rather slow to draw; expect about 20fps)
"""
## Add path to library (just for examples; you do not need this)
import initExample
import matplotlib as mpl
import matplotlib.cm as cm
from pyqtgraph.Qt import QtGui, QtCore, USE_PYSIDE
import numpy as np
import pyqtgraph as pg
from pyqtgraph.ptime import time
#QtGui.QApplication.setGraphicsSystem('raster')
app = QtGui.QApplication([])
#mw = QtGui.QMainWindow()
#mw.resize(800,800)
if USE_PYSIDE:
from ScatterPlotSpeedTestTemplate_pyside import Ui_Form
else:
from ScatterPlotSpeedTestTemplate_pyqt import Ui_Form
win = QtGui.QWidget()
win.setWindowTitle('pyqtgraph example: ScatterPlotSpeedTest')
ui = Ui_Form()
ui.setupUi(win)
win.show()
p = ui.plot
p.setRange(xRange=[-500, 500], yRange=[-500, 500])
data = np.random.normal(size=(50,10000), scale=100)
sizeArray = (np.random.random(500) * 20.).astype(int)
ptr = 0
lastTime = time()
fps = None
def update():
global curve, data, ptr, p, lastTime, fps
p.clear()
if ui.randCheck.isChecked():
size = sizeArray
else:
size = ui.sizeSpin.value()
z=np.random.randint(0,10000,10000)
norm = mpl.colors.Normalize(vmin=min(z), vmax=max(z))
m = cm.ScalarMappable(norm=norm, cmap=cm.jet)
colors = m.to_rgba(z, bytes=True)
colors_=[]
for i in colors:
colors_.append(pg.mkBrush(tuple(i)))
#colors.append(pg.intColor(np.random.randint(0,255), 100))
curve = pg.ScatterPlotItem(x=data[ptr%50], y=data[(ptr+1)%50],
pen='w', brush=colors_, size=size,
pxMode=ui.pixelModeCheck.isChecked())
'''
curve = pg.ScatterPlotItem(pen='w', size=size, pxMode=ui.pixelModeCheck.isChecked())
spots3=[]
for i,j,k in zip(data[ptr%50],data[(ptr+1)%50],colors):
spots3.append({'pos': (i, j), 'brush':pg.mkBrush(tuple(k))})
curve.addPoints(spots3)
'''
p.addItem(curve)
ptr += 1
now = time()
dt = now - lastTime
lastTime = now
if fps is None:
fps = 1.0/dt
else:
s = np.clip(dt*3., 0, 1)
fps = fps * (1-s) + (1.0/dt) * s
p.setTitle('%0.2f fps' % fps)
p.repaint()
#app.processEvents() ## force complete redraw for every plot
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(0)
## Start Qt event loop unless running in interactive mode.
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
I think that I have found a solution to my problem. It seems that ScatterPlotItem is simply too slow to continuously redraw large number of points (>500) with different colors specified by 'brush'. Instead, I am just using plotItem and 'symbolBrush' to color incoming data points with Jet colors (that will give me 2.5D plot I was initially searching for). The speed of the plot update is almost instant no matter how many data points are added, 100 points are recolored just as fast as 10000 points (from the user point of view).

Categories

Resources