Skip to content

Instantly share code, notes, and snippets.

@cpascual
Last active March 8, 2023 09:37
Show Gist options
  • Save cpascual/5620f913f83cae4be2a4f50057111e4c to your computer and use it in GitHub Desktop.
Save cpascual/5620f913f83cae4be2a4f50057111e4c to your computer and use it in GitHub Desktop.
InspectorLine : a simple example on how to inspect curve data with a moveable vertical line in pyqtgraph
from PyQt5 import Qt
from pyqtgraph import InfiniteLine, TextItem
import numpy as np
class InspectorLine(InfiniteLine):
def __init__(self, ):
super(InspectorLine, self).__init__(angle=90, movable=True)
self._labels = []
self._plot_item = None
self.sigPositionChanged.connect(self._onMoved)
def _onMoved(self):
x_px_size, _ = self.getViewBox().viewPixelSize()
inspector_x = self.value()
self._removeLabels()
points = []
# iterate over the existing curves
for c in self._plot_item.curves:
# find the index of the closest point of this curve
adiff = np.abs(c.xData - inspector_x)
idx = np.argmin(adiff)
# only add a label if the line touches the symbol
tolerance = .5 * max(1, c.opts['symbolSize']) * x_px_size
if adiff[idx] < tolerance:
points.append((c.xData[idx], c.yData[idx]))
self._createLabels(points)
def _createLabels(self, points):
for x, y in points:
text = 'x={}, y={}'.format(x, y)
text_item = TextItem(text=text)
text_item.setPos(x, y)
self._labels.append(text_item)
self._plot_item.addItem(text_item)
def _removeLabels(self):
# remove existing texts
for item in self._labels:
self._plot_item.removeItem(item)
self._labels = []
def attachToPlotItem(self, plot_item):
self._plot_item = plot_item
plot_item.addItem(self, ignoreBounds=True)
def dettach(self, plot_item):
self._removeLabels()
self._plot_item.removeItem(self)
self._plot_item = None
if __name__ == '__main__':
import pyqtgraph as pg
import sys
app = Qt.QApplication([])
plot = pg.PlotWidget()
c1 = pg.PlotDataItem(x=np.linspace(0.1, 10, 10),
y=np.random.rand(10),
symbol='o')
plot.addItem(c1)
c2 = pg.PlotDataItem(x=np.linspace(0.1, 10, 20),
y=1 + np.random.rand(20),
symbol='d')
plot.addItem(c2)
inspector = InspectorLine()
inspector.attachToPlotItem(plot.getPlotItem())
plot.show()
sys.exit(app.exec_())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment