Search code examples
pythonpython-3.xpyqt5pyqtgraph

Pyqtgraph color specific regions in plot


I've been using matplotlib.collections up until now and it was fairly simple to mark a collection with a different color.

My current project requires me to use pyqtgraph to do the same.

self.plot = pg.PlotWidget()
layout.addWidget(self.plot)

If the index i of bool array is true then that corresponding index i of float has to be colored (vertically or broken horizontal bars).

Example:

y = [50, 100, 50, 250, 150]
x = [1, 5, 87, 92, 106]
b = [False, False, True, False, True]

After plotting 87 and 106 should be highlighted through vertical bars over x axis with some color or mark. Any hints?


Solution

  • I'm not totally clear on the visualization you have in mind, but here are a couple of options for marking your selected points:

    1. Use a single instance of pg.VTickGroup to draw ticks along the x axis
    2. Use many instances of pg.InfiniteLine to draw lines and other marking shapes

    Example:

    import pyqtgraph as pg
    import numpy as np
    
    plt = pg.plot()
    
    y = [50, 100, 50, 250, 150]
    x = [1, 5, 87, 92, 106]
    b = [False, False, True, False, True]
    
    # draw a scatter plot with selected points in yellow
    cmap = {False: (0, 0, 200), True: (255, 255, 0)}
    brushes = [pg.mkBrush(cmap[x]) for x in b]
    plt.plot(x, y, pen=None, symbol='o', symbolBrush=brushes)
    
    # draw vertical ticks marking the position of selected points
    tick_x = np.array(x)[b]
    ticks = pg.VTickGroup(tick_x, yrange=[0, 0.1], pen={'color': 'w', 'width': 5})
    plt.addItem(ticks)
    
    # add a vertical line with marker at the bottom for each selected point
    for tx in tick_x:
        l = plt.addLine(x=tx, pen=(50, 150, 50), markers=[('^', 0, 10)])