How do I clear a ScatterPlotItem in PYQTGRAPH

Question:

I am attempting to move a “cursor” around my graph using ScatterPlotItem and a ‘+’ symbol as the cursor. The cursor updates its position perfectly but I cannot figure out how to clear the last instance. Here is the line that I use to plot the ‘cursor’.

self.cursor2 = self.p2_3.addItem(pg.ScatterPlotItem([self.xx], [self.yy], pen=None, symbol='+', color = 'b'))

I tried self.cursor2.clear() but that didn’t work. Any help is appreciated.

Asked By: Mike C.

||

Answers:

When you call addItem you add the plotdataitem, in this case a scatterplotitem to your plotitem. To remove it you call removeItem in the same way. But you need to keep a reference to the scatterplotitem to do that.

Note that addItem doesn’t return anything i.e. your self.cursor2 is None.

If you want to remove everything from your plot you could call

self.p2_3.clear()

otherwise to just remove the scatterplotitem you can do like this

import pyqtgraph as pg

win = pg.GraphicsWindow()
plotitem = win.addPlot()
scatterplot = pg.ScatterPlotItem([2], [3], symbol='+', color = 'b')

plotitem.addItem(scatterplot)
plotitem.removeItem(scatterplot)
Answered By: luddek

I would suggest to use setData to control ScatterPlotItem data instead of creating/adding/removing the object each time the mouse is moving:

# This just once:
self.scatterplot = pg.ScatterPlotItem(x=[], y=[], symbol='+', color = 'b')
plotitem.addItem(self.scatterplot)


# On mouse hovering:
self.scatterplot.setData(x=[self.xx], y=[self.yy])

It’s way more efficient.

Answered By: Buzz
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.