I have a sample code that produces a standard scatterplot with pairs of X & Y. For the project I'm working on, we cannot use matplotlib, but stick to pyqtgraph instead (it is part of a PyQt project).
from PyQt4 import QtGui
import pyqtgraph as pg
import pyqtgraph.exporters
import numpy as np
x = np.random.normal(size=100)
y = np.random.normal(size=100)
app = QtGui.QApplication([]) # create the application
w = QtGui.QWidget()
pwidget = pg.PlotWidget()
pwidget.addLegend(size=(100, 10)) # add a legend
pwidget.plot(x, y, pen=None, symbol="o", name="My Data") # plot the data
line = pg.InfiniteLine(angle=45, movable=False) # add a line through origin
pwidget.addItem(line)
pwidget.setXRange(-3, 3)
pwidget.setYRange(-3, 3)
layout = QtGui.QGridLayout()
w.setLayout(layout)
layout.addWidget(pwidget)
w.show()
app.exec_()
Now this code works just fine and does, what it should do. This is a screenshot of the popup window:
When trying to export like this, however:
exporter = pg.exporters.ImageExporter(pwidget.plotItem)
exporter.export('D:/file_example.png')
I get the following error:
File
"C:\OSGeo4W64\apps\Python27\Lib\site-packages\pyqtgraph\exporters\ImageExporter.py",
line 70, in export
bg = np.empty((self.params['width'], self.params['height'], 4), dtype=np.ubyte) TypeError: 'float' object cannot be interpreted as an
index
Dr. Google showed me that this may be a bug of the version I (have to) use and that there is the workaround of setting width and height manually. So I updated the code like this:
exporter = pg.exporters.ImageExporter(pwidget.plotItem)
exporter.params.param('width').setValue(1024, blockSignal=exporter.widthChanged)
exporter.params.param('height').setValue(860, blockSignal=exporter.heightChanged)
exporter.export('D:/file_example.png')
with the following rather disturbing result:
I played around with the exporter.params, but nothing changed the result.
Any ideas are highly appreciated, thanks!
Related
Question:
I am struggling for a more than a week now to do something probably pretty simple:
I want to make a time series plot in which i can control the x axis
range/zoom with a datetime picker widget.
I also want the datetime picker to be updated when the x range is
changed with the plot zoom controls
So far I can do either but not both. It did work for other widgets such as the intslider etc.
Requirements:
If the solution has 1 DatetimeRangePicker to define the x range or 2 DatetimePicker widgets (one for start one for end) would both work great for me.
my datasets are huge so it would be great if it works with datashader
Any help is much appreciated :)
What I tried:
MRE & CODE BELOW
Create a DatetimeRangePicker widget, plot the data using pvplot and set the xlim=datatimerangepicker.
Result: the zoom changes with the selected dates on the widget, but zooming / panning the plot does not change the values of the widget.
Use hv.streams.RangeX stream to capture changes in x range when panning / zooming. Use a pn.depends function to generate plot when changing DatetimeRangePicker widget.
Result: the figure loads and zooming/panning changes the widget (but is very slow), but setting the widget causes AttributeError.
Create a DatetimePicker widget for start and end. Link them with widget.jslink() bidirectionally to x_range.start and x_range.end of the figure.
Result: figure loads but nothing changes when changing values on the widget or panning/zooming.
MRE & Failed Attempts
Create Dataset
import pandas as pd
import numpy as np
import panel as pn
import holoviews as hv
import hvplot.pandas
hv.extension('bokeh')
df = pd.DataFrame({'data': np.random.randint(0, 100, 100)}, index=pd.date_range(start="2022", freq='D', periods=100))
Failed Method 1:
plot changes with widget, but widget does not change with plot
range_select = pn.widgets.DatetimeRangePicker(value=(df.index[0], df.index[-1]))
pn.Column(df.data.hvplot.line(datashade=True, xlim=range_select), range_select)
Failed Method 2:
Slow and causes AttributeError: 'NoneType' object has no attribute 'id' when changing widget
range_select = pn.widgets.DatetimeRangePicker(value=(df.index[0], df.index[-1]))
#pn.depends(range_x=range_select.param.value)
def make_fig(range_x):
fig = df.data.hvplot.line(datashade=True, xlim=range_x)
pointer = hv.streams.RangeX(source=fig)
tabl = hv.DynamicMap(show_x, streams=[pointer]) # plot useless table to make it work
return fig + tabl
def show_x(x_range):
if x_range is not None:
range_select.value = tuple([pd.Timestamp(i).to_pydatetime() for i in x_range])
return hv.Table({"start": [x_range[0]], "stop": [x_range[1]]}, ["start", "stop"]) if x_range else hv.Table({})
pn.Column(range_select, make_fig)
Failed Method 3:
does not work with DatetimePicker widget, but does work other widgets (e.g. intslider)
pn.widgets.DatetimePicker._source_transforms = ({}) # see https://discourse.holoviz.org/t/using-jslink-with-pn-widgets-datepicker/1116
# datetime range widgets
range_strt = pn.widgets.DatetimePicker()
range_end = pn.widgets.DatetimePicker()
# int sliders as example that some widgets work
int_start_widget = pn.widgets.IntSlider(start=0, step=int(1e6), end=int(1.7e12))
int_end_widget = pn.widgets.IntSlider(start=0, step=int(1e6), end=int(1.7e12))
points = df.data.hvplot.line(datashade=True) # generate plot
# link widgets to plot:
int_start_widget.jslink(points, value="x_range.start", bidirectional=True)
int_end_widget.jslink(points, value="x_range.end", bidirectional=True)
range_strt.jslink(points, value="x_range.start", bidirectional=True)
range_end.jslink(points, value="x_range.end", bidirectional=True)
pn.Row(points,pn.Column( range_strt, range_end, int_start_widget, int_end_widget,))
Here is what I came up with:
range_select = pn.widgets.DatetimeRangePicker(value=(df.index[0].to_pydatetime(), df.index[-1].to_pydatetime()))
curve = df.data.hvplot.line(datashade=True).apply.opts(xlim=range_select, framewise=True)
rxy = hv.streams.RangeX(source=curve)
def update_widget(event):
new_dates = tuple([pd.Timestamp(i).to_pydatetime() for i in event.new])
if new_dates != range_select.value:
range_select.value = new_dates
rxy.param.watch(update_widget, 'x_range')
pn.Column(range_select, curve)
Basically we use .apply.opts to apply current widget value as the xlim dynamically (and set framewise=True so the plot ranges update dynamically). Then we instantiate a RangeX stream which we use to update the widget value. Annoyingly we have to do some datetime conversions because np.datetime64 and Timestamps aren't supported in some cases.
I am trying to animate a plot using visvis.
This is the example code they have:
import visvis as vv
# read image
ims = [vv.imread('astronaut.png')]
# make list of images: decrease red channel in subsequent images
for i in range(9):
im = ims[i].copy()
im[:,:,0] = im[:,:,0]*0.9
ims.append(im)
# create figure, axes, and data container object
a = vv.gca()
m = vv.MotionDataContainer(a)
# create textures, loading them into opengl memory, and insert into container.
for im in ims:
t = vv.imshow(im)
t.parent = m
and I added:
app = vv.use()
app.Run()
This worked. But I needed to animate a plot, not an image, so I tried doing this:
import visvis as vv
from visvis.functions import getframe
# create figure, axes, and data container object
a = vv.gca()
m = vv.MotionDataContainer(a, interval=100)
for i in range(3):
vv.plot([0, 2+i*10], [0, 2+i*10])
f = getframe(a)
t = vv.imshow(f)
t.parent = m
a.SetLimits(rangeX=[-2, 25], rangeY=[-2, 25])
app = vv.use()
app.Run()
The axes are being initialized very big, that is why I am using set limits, and the output is not animated. I am getting only the last frame so a line from (0,0) to (22, 22).
Does anyone know a way of doing this with visvis?
It turns out adding the frame as a child of MotionDataContainer was not the way to go. The function vv.plot returns an instance of the class Line, and one should add the line as a child. If anyone is having the same problem, I could write a more detailed answer.
EDIT Adding a more detailed answer as requested:
To animate a plot made of lines, one must simply add the lines as children of MotionDataContainer. Taking my example in the question above, one would write:
import visvis as vv
# create figure, axes, and data container object
a = vv.gca()
m = vv.MotionDataContainer(a, interval=100)
for i in range(3):
line = vv.plot([0, 2+i*10], [0, 2+i*10])
line.parent = m
app = vv.use()
app.Run()
In my special case, I even needed to animate multiple lines being drawn at the same time.
To do this, I ended up defining a new class that, like MotionDataContainer, also inherits from MotionMixin, and change the class attribute delta which specifies how many objects should be made visible at the same time. For that, one has to also rewrite the function _SetMotionIndex.
(See visvis official source code: https://github.com/almarklein/visvis/blob/master/wobjects/motion.py)
Disclaimer: Concerning the animation of multiple objects, I have no idea if this is the intended use or if this is the easiest solution, but this is what worked for me.
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_()
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_())
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.