Skip to main content
`Ctrl`+`K`

# Package structure

The `silx.gui.plot` package provides plot widgets. This package is structured as follows.

`PlotWidget` and `PlotWindow` provides the user API. `PlotWidget` is a Qt widget (actually a `QMainWindow`) displaying a 1D, 2D plot area. It provides different interaction modes. `PlotWindow` is a Qt widget (actually a `QMainWindow`) which adds a set of toolbar buttons and associated functionalities to `PlotWidget`. The toolbar QActions are implemented in `actions`.

`Plot`, `PlotEvents` and `PlotInteraction` implement the plotting API regardless of the rendering backend and regardless of its integration in Qt. The plotting API in defined in `Plot`. The different interaction modes (zoom, drawing, pan) are implemented in `PlotInteraction`. Each interaction mode is implemented with a state machine structure (implemented in `Interaction`). The different events emitted by `Plot` and by the interaction modes are created with helper functions defined in `PlotEvents`.

The `PlotWindow` uses additional widgets:

- `CurvesROIWidget` to create regions of interest for curves

- `LegendSelector` to display a list of curves legends which provides some control on the curves (e.g., select, delete).

- `MaskToolsWidget` to provide tools to draw a mask on an image.

- `ScatterMaskToolsWidget` to provide tools to draw a mask on a scatter.

- The `PlotTools` module provides a set of additional widgets:

  - `PlotTools.PositionInfo`

  - `PlotTools.LimitsToolBar`

- The `Profile` module provides toolbar for extracting profiles from image and image stack:

  - `Profile.ProfileToolBar`

  - `Profile.Profile3DToolBar`

- `silx.gui.console` to provide an IPython console which can control the plot area content.

The widgets also use the following miscellaneous modules:

- `_utils`: utility functions

The `backends` package provide the implementation of the rendering used by the `Plot`. It contains: `backends.BackendBase` defines the API any plot backend should provide in `BackendBase`. `backends.BackendMatplotlib` implements a matplotlib backend. The `backends.BackendMatplotlib` the provides two classes:

- `BackendMatplotlib` that provides a matplotlib backend without a specific canvas.

- `BackendMatplotlibQt` which inherits from `BackendMatplotlib` and adds a Qt canvas, and Qt specific functionalities.

The OpenGL-based backend is implemented in the `backends.BackendOpenGL` module and the `backends.glutils` package which provides the different primitives used for rendering and interaction. It is based on `silx.gui._glutils`, PyOpenGL and OpenGL >= 2.1.

# Modules

For `PlotWidget` and `Plot` modules, see their respective documentations: `PlotWidget`, `Plot`.

The following modules are the modules used internally by the plot package.

## `backends.BackendBase`

Base class for Plot backends.

It documents the Plot backend API.

This API is a simplified version of PyMca PlotBackend API.

class BackendBase(plot, parent=None)

  Class defining the API a backend of the Plot should provide.

  addCurve(x, y, color, gapcolor, symbol, linewidth, linestyle, yaxis, xerror, yerror, fill, alpha, symbolsize, baseline)

    Add a 1D curve given by x an y to the graph.

    Parameters:

      - x (numpy.ndarray) – The data corresponding to the x axis

      - y (numpy.ndarray) – The data corresponding to the y axis

      - color (string ("#RRGGBB") or (npoints, 4) unsigned byte array or one of the predefined color names defined in colors.py) – color(s) to be used

      - gapcolor (Union[str, None]) – color used to fill dashed line gaps.

      - symbol (str) –

        Symbol to be drawn at each (x, y) position:

            - ' ' or '' no symbol
            - 'o' circle
            - '.' point
            - ',' pixel
            - '+' cross
            - 'x' x-cross
            - 'd' diamond
            - 's' square

      - linewidth (float) – The width of the curve in pixels

      - linestyle –

        Type of line:

            - ' ' or ''  no line
            - '-'  solid line
            - '--' dashed line
            - '-.' dash-dot line
            - ':'  dotted line
            - (offset, (dash pattern))

      - yaxis (str) – The Y axis this curve belongs to in: ‘left’, ‘right’

      - xerror (numpy.ndarray or None) – Values with the uncertainties on the x values

      - yerror (numpy.ndarray or None) – Values with the uncertainties on the y values

      - fill (bool) – True to fill the curve, False otherwise

      - alpha (float) – Curve opacity, as a float in [0., 1.]

      - symbolsize (float) – Size of the symbol (if any) drawn at each (x, y) position.

    Returns:

      The handle used by the backend to univocally access the curve

  addImage(data, origin, scale, colormap, alpha)

    Add an image to the plot.

    Parameters:

      - data (numpy.ndarray) – (nrows, ncolumns) data or (nrows, ncolumns, RGBA) ubyte array

      - origin (2-tuple of float) – (origin X, origin Y) of the data. Default: (0., 0.)

      - scale (2-tuple of float) – (scale X, scale Y) of the data. Default: (1., 1.)

      - colormap (Colormap) – Colormap object to use. Ignored if data is RGB(A).

      - alpha (float) – Opacity of the image, as a float in range [0, 1].

    Returns:

      The handle used by the backend to univocally access the image

  addTriangles(x, y, triangles, color, alpha)

    Add a set of triangles.

    Parameters:

      - x (numpy.ndarray) – The data corresponding to the x axis

      - y (numpy.ndarray) – The data corresponding to the y axis

      - triangles (numpy.ndarray) – The indices to make triangles as a (Ntriangle, 3) array

      - color (numpy.ndarray) – color(s) as (npoints, 4) array

      - alpha (float) – Opacity as a float in [0., 1.]

    Returns:

      The triangles’ unique identifier used by the backend

  addShape(x, y, shape, color, fill, overlay, linestyle, linewidth, gapcolor)

    Add an item (i.e. a shape) to the plot.

    Parameters:

      - x (numpy.ndarray) – The X coords of the points of the shape

      - y (numpy.ndarray) – The Y coords of the points of the shape

      - shape (str) – Type of item to be drawn in hline, polygon, rectangle, vline, polylines

      - color (str) – Color of the item

      - fill (bool) – True to fill the shape

      - overlay (bool) – True if item is an overlay, False otherwise

      - linestyle –

        Style of the line. Only relevant for line markers where X or Y is None. Value in:

        - ’ ‘ no line

        - ’-’ solid line

        - ’–’ dashed line

        - ’-.’ dash-dot line

        - ’:’ dotted line

        - (offset, (dash pattern))

      - linewidth (float) – Width of the line. Only relevant for line markers where X or Y is None.

      - gapcolor (str) – Background color of the line, e.g., ‘blue’, ‘b’, ‘#FF0000’. It is used to draw dotted line using a second color.

    Returns:

      The handle used by the backend to univocally access the item

  addMarker(x, y, text, color, symbol, symbolsize, linestyle, linewidth, constraint, yaxis, font, bgcolor)

    Add a point, vertical line or horizontal line marker to the plot.

    Parameters:

      - x (`float` | `None`) – Horizontal position of the marker in graph coordinates. If None, the marker is a horizontal line.

      - y (`float` | `None`) – Vertical position of the marker in graph coordinates. If None, the marker is a vertical line.

      - text (`str` | `None`) – Text associated to the marker (or None for no text)

      - color (`str`) – Color to be used for instance ‘blue’, ‘b’, ‘#FF0000’

      - bgcolor (`Tuple`[`float`, `float`, `float`, `float`] | `None`) – Text background color to be used for instance ‘blue’, ‘b’, ‘#FF0000’

      - symbol (`str` | `None`) –

        Symbol representing the marker. Only relevant for point markers where X and Y are not None. Value in:

        - ’o’ circle

        - ’.’ point

        - ’,’ pixel

        - ’+’ cross

        - ’x’ x-cross

        - ’d’ diamond

        - ’s’ square

      - linestyle (`str` | `tuple`[`float`, `tuple`[`float`, `...`] | `None`]) –

        Style of the line. Only relevant for line markers where X or Y is None. Value in:

        - ’ ‘ no line

        - ’-’ solid line

        - ’–’ dashed line

        - ’-.’ dash-dot line

        - ’:’ dotted line

        - (offset, (dash pattern))

      - linewidth (`float`) – Width of the line. Only relevant for line markers where X or Y is None.

      - constraint (`Callable`[[`float`, `float`], `tuple`[`float`, `float`]] | `None`) – A function filtering marker displacement by dragging operations or None for no filter. This function is called each time a marker is moved. It takes the coordinates of the current cursor position in the plot as input and that returns the filtered coordinates.

      - yaxis (`str`) – The Y axis this marker belongs to in: ‘left’, ‘right’

      - font (`QFont`) – QFont to use to render text

      - symbolsize (`float`)

    Return type:

      `object`

    Returns:

      Handle used by the backend to univocally access the marker

  remove(item)

    Remove an existing item from the plot.

    Parameters:

      item – A backend specific item handle returned by a add* method

  setGraphCursorShape(cursor)

    Set the cursor shape.

    To override in interactive backends.

    Parameters:

      cursor (str) – Name of the cursor shape or None

  setGraphCursor(flag, color, linewidth, linestyle)

    Toggle the display of a crosshair cursor and set its attributes.

    To override in interactive backends.

    Parameters:

      - flag (bool) – Toggle the display of a crosshair cursor.

      - color (A string (either a predefined color name in colors.py or "#RRGGBB")) or a 4 columns unsigned byte array.) – The color to use for the crosshair.

      - linewidth (int) – The width of the lines of the crosshair.

      - linestyle (None, one of the predefined styles or (offset, (dash pattern)).) –

        Type of line:

            - ' ' no line
            - '-' solid line
            - '--' dashed line
            - '-.' dash-dot line
            - ':' dotted line
            - (offset, (dash pattern))

  getItemsFromBackToFront(condition=None)

    Returns the list of plot items order as rendered by the backend.

    This is the order used for rendering. By default, it takes into account overlays, z value and order of addition of items, but backends can override it.

    Parameters:

      condition (callable) – Callable taking an item as input and returning False for items to skip. If None (default), no item is skipped.

    Return type:

      List[Item]

  pickItem(x, y, item)

    Return picked indices if any, or None.

    Parameters:

      - x (float) – The x pixel coord where to pick.

      - y (float) – The y pixel coord where to pick.

      - item – A backend item created with add* methods.

    Returns:

      None if item was not picked, else returns picked indices information.

    Return type:

      Union[None,List]

  setCurveColor(curve, color)

    Set the color of a curve.

    Parameters:

      - curve – The curve handle

      - color (str) – The color to use.

  getWidgetHandle()

    Return the widget this backend is drawing to.

  postRedisplay()

    Trigger backend update and repaint.

  replot()

    Redraw the plot.

  saveGraph(fileName, fileFormat, dpi)

    Save the graph to a file (or a StringIO)

    At least “png”, “svg” are supported.

    Parameters:

      - fileName (String or StringIO or BytesIO) – Destination

      - fileFormat (str) – String specifying the format

      - dpi (int) – The resolution to use or None.

  setGraphTitle(title)

    Set the main title of the plot.

    Parameters:

      title (str) – Title associated to the plot

  setGraphXLabel(label)

    Set the X axis label.

    Parameters:

      label (str) – label associated to the plot bottom X axis

  setGraphYLabel(label, axis)

    Set the left Y axis label.

    Parameters:

      - label (str) – label associated to the plot left Y axis

      - axis (str) – The axis for which to get the limits: left or right

  setLimits(xmin, xmax, ymin, ymax, y2min=None, y2max=None)

    Set the limits of the X and Y axes at once.

    Parameters:

      - xmin (float) – minimum bottom axis value

      - xmax (float) – maximum bottom axis value

      - ymin (float) – minimum left axis value

      - ymax (float) – maximum left axis value

      - y2min (float) – minimum right axis value

      - y2max (float) – maximum right axis value

  getGraphXLimits()

    Get the graph X (bottom) limits.

    Returns:

      Minimum and maximum values of the X axis

  setGraphXLimits(xmin, xmax)

    Set the limits of X axis.

    Parameters:

      - xmin (float) – minimum bottom axis value

      - xmax (float) – maximum bottom axis value

  getGraphYLimits(axis)

    Get the graph Y (left) limits.

    Parameters:

      axis (str) – The axis for which to get the limits: left or right

    Returns:

      Minimum and maximum values of the Y axis

  setGraphYLimits(ymin, ymax, axis)

    Set the limits of the Y axis.

    Parameters:

      - ymin (float) – minimum left axis value

      - ymax (float) – maximum left axis value

      - axis (str) – The axis for which to get the limits: left or right

  getXAxisTimeZone()

    Returns tzinfo that is used if the X-Axis plots date-times.

    None means the datetimes are interpreted as local time.

    Return type:

      datetime.tzinfo of None.

  setXAxisTimeZone(tz)

    Sets tzinfo that is used if the X-Axis plots date-times.

    Use None to let the datetimes be interpreted as local time.

    Return type:

      datetime.tzinfo of None.

  isXAxisTimeSeries()

    Return True if the X-axis scale shows datetime objects.

    Return type:

      bool

  setXAxisTimeSeries(isTimeSeries)

    Set whether the X-axis is a time series

    Parameters:

      flag (bool) – True to switch to time series, False for regular axis.

  setXAxisLogarithmic(flag)

    Set the X axis scale between linear and log.

    Parameters:

      flag (bool) – If True, the bottom axis will use a log scale

  setYAxisLogarithmic(flag)

    Set the Y axis scale between linear and log.

    Parameters:

      flag (bool) – If True, the left axis will use a log scale

  setYAxisInverted(flag)

    Invert the Y axis.

    Parameters:

      flag (bool) – If True, put the vertical axis origin on the top

  isYAxisInverted()

    Return True if left Y axis is inverted, False otherwise.

  isYRightAxisVisible()

    Return True if the Y axis on the right side of the plot is visible

    Return type:

      `bool`

  isKeepDataAspectRatio()

    Returns whether the plot is keeping data aspect ratio or not.

  setKeepDataAspectRatio(flag)

    Set whether to keep data aspect ratio or not.

    Parameters:

      flag (Boolean, default True) – True to respect data aspect ratio

  setGraphGrid(which)

    Set grid.

    Parameters:

      which – None to disable grid, ‘major’ for major grid, ‘both’ for major and minor grid

  dataToPixel(x, y, axis)

    Convert a position in data space to a position in pixels in the widget.

    Parameters:

      - x (float or sequence of float) – The X coordinate in data space.

      - y (float or sequence of float) – The Y coordinate in data space.

      - axis (str) – The Y axis to use for the conversion (‘left’ or ‘right’).

    Returns:

      The corresponding position in pixels or None if the data position is not in the displayed area.

    Return type:

      A tuple of 2 floats: (xPixel, yPixel) or None.

  pixelToData(x, y, axis)

    Convert a position in pixels in the widget to a position in the data space.

    Parameters:

      - x (float) – The X coordinate in pixels.

      - y (float) – The Y coordinate in pixels.

      - axis (str) – The Y axis to use for the conversion (‘left’ or ‘right’).

    Returns:

      The corresponding position in data space or None if the pixel position is not in the plot area.

    Return type:

      A tuple of 2 floats: (xData, yData) or None.

  getPlotBoundsInPixels()

    Plot area bounds in widget coordinates in pixels.

    Returns:

      bounds as a 4-tuple of int: (left, top, width, height)

  setAxesMargins(left, top, right, bottom)

    Set the size of plot margins as ratios.

    Values are expected in [0., 1.]

    Parameters:

      - left (`float`)

      - top (`float`)

      - right (`float`)

      - bottom (`float`)

      - left

      - top

      - right

      - bottom

  setForegroundColors(foregroundColor, gridColor)

    Set foreground and grid colors used to display this widget.

    Parameters:

      - foregroundColor (List[float]) – RGBA foreground color of the widget

      - gridColor (List[float]) – RGBA grid color of the data view

  setBackgroundColors(backgroundColor, dataBackgroundColor)

    Set background colors used to display this widget.

    Parameters:

      - backgroundColor (List[float]) – RGBA background color of the widget

      - dataBackgroundColor (Union[Tuple[float],None]) – RGBA background color of the data view

## `CurvesROIWidget`

Widget to handle regions of interest (`ROI`) on curves displayed in a `PlotWindow`.

This widget is meant to work with `PlotWindow`.

class CurvesROIWidget(parent=None, name=None, plot=None)

  Widget displaying a table of ROI information.

  Implements also the following behavior:

  - if the roiTable has no ROI when showing create the default ICR one

  Parameters:

    - parent – See `QWidget`

    - name (str) – The title of this widget

  sigROIWidgetSignal

    Signal of ROIs modifications.

    Modification information if given as a dict with an ‘event’ key providing the type of events.

    Type of events:

    - AddROI, DelROI, LoadROI and ResetROI with keys: ‘roilist’, ‘roidict’

    - selectionChanged with keys: ‘row’, ‘col’ ‘roi’, ‘key’, ‘colheader’, ‘rowheader’

  getPlotWidget()

    Returns the associated PlotWidget or None

    Return type:

      Union[PlotWidget,None]

  property roiFileDir

    The directory from which to load/save ROI from/to files.

  load(filename)

    Load ROI widget information from a file storing a dict of ROI.

    Parameters:

      filename (str) – The file from which to load ROI

  save(filename)

    Save current ROIs of the widget as a dict of ROI to a file.

    Parameters:

      filename (str) – The file to which to save the ROIs

  setHeader(text='ROIs')

    Set the header text of this widget

  calculateRois(roiList=None, roiDict=None)

    Compute ROI information

  showEvent(self, a0: QShowEvent | None)
  hideEvent(self, a0: QHideEvent | None)

class ROITable(parent=None, plot=None, rois=None)

  Table widget displaying ROI information.

  See `QTableWidget` for constructor arguments.

  Behavior: listen at the active curve changed only when the widget is visible. Otherwise won’t compute the row and net counts…

  activeROIChanged

    Signal emitted when the active roi changed or when the value of the active roi are changing

  clear()

    Note

    clear the interface only. keep the roidict…

  setRois(rois, order=None)

    Set the ROIs by providing a dictionary of ROI information.

    The dictionary keys are the ROI names. Each value is a sub-dictionary of ROI info with the following fields:

    - `"from"`: x coordinate of the left limit, as a float

    - `"to"`: x coordinate of the right limit, as a float

    - `"type"`: type of ROI, as a string (e.g “channels”, “energy”)

    Parameters:

      - roidict – Dictionary of ROIs

      - order (str) – Field used for ordering the ROIs. One of “from”, “to”, “type”. None (default) for no ordering, or same order as specified in parameter `rois` if provided as a dict.

  addRoi(roi)

    :param `ROI` roi: roi to add to the table

  deleteActiveRoi()

    remove the current active roi

  removeROI(roi)

    remove the requested roi

    Parameters:

      name (str) – the name of the roi to remove from the table

  setActiveRoi(roi)

    Define the given roi as the active one.

    Warning

    this roi should already be registred / added to the table

    :param `ROI` roi: the roi to defined as active

  currentChanged(self, current: QModelIndex, previous: QModelIndex)
  calculateRois()

    Update values of all registred rois (raw and net counts in particular)

  getRois(order)

    Return the currently defined ROIs, as an ordered dict.

    The dictionary keys are the ROI names. Each value is a `ROI` object..

    Parameters:

      order – Field used for ordering the ROIs. One of “from”, “to”, “type”, “netcounts”, “rawcounts”. None (default) to get the same order as displayed in the widget.

    Returns:

      Ordered dictionary of ROI information

  save(filename)

    Save current ROIs of the widget as a dict of ROI to a file.

    Parameters:

      filename (str) – The file to which to save the ROIs

  load(filename)

    Load ROI widget information from a file storing a dict of ROI.

    Parameters:

      filename (str) – The file from which to load ROI

  showAllMarkers(_show=True)
    Parameters:

      _show (bool) – if true show all the markers of all the ROIs boundaries otherwise will only show the one of the active ROI.

  setMiddleROIMarkerFlag(flag=True)

    Activate or deactivate middle marker.

    This allows shifting both min and max limits at once, by dragging a marker located in the middle.

    Parameters:

      flag (bool) – True to activate middle ROI marker

  showEvent(self, a0: QShowEvent | None)
  hideEvent(self, a0: QHideEvent | None)
  setCountsVisible(visible)

    Display the columns relative to areas or not

    Parameters:

      visible (bool) – True if the columns ‘Raw Area’ and ‘Net Area’ should be visible.

  setAreaVisible(visible)

    Display the columns relative to areas or not

    Parameters:

      visible (bool) – True if the columns ‘Raw Area’ and ‘Net Area’ should be visible.

  fillFromROIDict(roilist=(), roidict=None, currentroi=None)

    This function API is kept for compatibility. But setRois should be preferred.

    Set the ROIs by providing a list of ROI names and a dictionary of ROI information for each ROI. The ROI names must match an existing dictionary key. The name list is used to provide an order for the ROIs. The dictionary’s values are sub-dictionaries containing 3 mandatory fields:

    - `"from"`: x coordinate of the left limit, as a float

    - `"to"`: x coordinate of the right limit, as a float

    - `"type"`: type of ROI, as a string (e.g “channels”, “energy”)

    Parameters:

      - roilist (List) – List of ROI names (keys of roidict)

      - roidict (dict) – Dict of ROI information

      - currentroi – Name of the selected ROI or None (no selection)

class ROI(name, fromdata=None, todata=None, type_=None)

  The Region Of Interest is defined by:

  - A name

  - A type. The type is the label of the x axis. This can be used to apply or not some ROI to a curve and do some post processing.

  - The x coordinate of the left limit (fromdata)

  - The x coordinate of the right limit (todata)

  Parameters:

    - str – name of the ROI

    - fromdata – left limit of the roi

    - todata – right limit of the roi

    - type – type of the ROI

  sigChanged

    Signal emitted when the ROI is edited

  getID()
    Return int:

      the unique ID of the ROI

  setType(type_)
    Parameters:

      type (str)

  getType()
    Return str:

      the type of the ROI.

  setFrom(frm)
    Parameters:

      frm – set x coordinate of the left limit

  getFrom()
    Returns:

      x coordinate of the left limit

  setTo(to)
    Parameters:

      to – x coordinate of the right limit

  getTo()
    Returns:

      x coordinate of the right limit

  getMiddle()
    Returns:

      middle position between ‘from’ and ‘to’ values

  toDict()
    Returns:

      dict containing the roi parameters

  isICR()
    Returns:

      True if the ROI is the ICR

  computeRawAndNetCounts(curve)

    Compute the Raw and net counts in the ROI for the given curve.

    - Raw count: Points values sum of the curve in the defined Region Of

        Interest.

    - Net count: Raw counts minus background

    Parameters:

      curve (CurveItem)

    Return tuple:

      rawCount, netCount

  computeRawAndNetArea(curve)

    Compute the Raw and net counts in the ROI for the given curve.

    - Raw area: integral of the curve between the min ROI point and the

        max ROI point to the y = 0 line.

    - Net area: Raw counts minus background

    Parameters:

      curve (CurveItem)

    Return tuple:

      rawArea, netArea

  contains(position)

    Returns True if the position is in this ROI.

    Parameters:

      position (tuple[float,float]) – position to check

    Returns:

      True if the value / point is consider to be in the region of interest.

    Return type:

      bool

class CurvesROIDockWidget(parent=None, plot=None, name=None)

  QDockWidget with a `CurvesROIWidget` connected to a PlotWindow.

  It makes the link between the `CurvesROIWidget` and the PlotWindow.

  Parameters:

    - parent – See `QDockWidget`

    - plot – `PlotWindow` instance on which to operate

    - name – See `QDockWidget`

  sigROISignal

    Deprecated signal for backward compatibility with silx < 0.7. Prefer connecting directly to `CurvesRoiWidget.sigRoiSignal`

  roiWidget

    Main widget of type `CurvesROIWidget`

  toggleViewAction()

    Returns a checkable action that shows or closes this widget.

    See `QMainWindow`.

## `Interaction`

This module provides an implementation of state machines for interaction.

Sample code of a state machine with two states (‘idle’ and ‘active’) with transitions on left button press/release:

    from silx.gui.plot.Interaction import *

    class SampleStateMachine(StateMachine):

        class Idle(State):
            def onPress(self, x, y, btn):
                if btn == LEFT_BTN:
                    self.goto('active')

        class Active(State):
            def enterState(self):
                print('Enabled')  # Handle enter active state here

            def leaveState(self):
                print('Disabled')  # Handle leave active state here

            def onRelease(self, x, y, btn):
                if btn == LEFT_BTN:
                    self.goto('idle')

    def __init__(self):
        # State machine has 2 states
        states = {
            'idle': SampleStateMachine.Idle,
            'active': SampleStateMachine.Active
        }
        super(TwoStates, self).__init__(states, 'idle')
        # idle is the initial state

    stateMachine = SampleStateMachine()

    # Triggers a transition to the Active state:
    stateMachine.handleEvent('press', 0, 0, LEFT_BTN)

    # Triggers a transition to the Idle state:
    stateMachine.handleEvent('release', 0, 0, LEFT_BTN)

See `ClickOrDrag` for another example of a state machine.

See Renaud Blanch, Michel Beaudouin-Lafon. Programming Rich Interactions using the Hierarchical State Machine Toolkit. In Proceedings of AVI 2006. p 51-58. for a discussion of using (hierarchical) state machines for interaction.

class State(machine)

  Base class for the states of a state machine.

  This class is meant to be subclassed.

  property machine

    The state machine this state belongs to.

    Useful to access data or methods that are shared across states.

  goto(state, *args, **kwargs)

    Performs a transition to a new state.

    Extra arguments are passed to the `enterState()` method of the new state.

    Parameters:

      state (str) – The name of the state to go to.

  enterState(*args, **kwargs)

    Called when the state machine enters this state.

    Arguments are those provided to the `goto()` method that triggered the transition to this state.

  leaveState()

    Called when the state machine leaves this state (i.e., when `goto()` is called).

  validate()

    Called externally to validate the current interaction in case of a creation.

class StateMachine(states, initState, *args, **kwargs)

  State machine controller.

  This is the entry point of a state machine. It is in charge of dispatching received event and handling the current active state.

  handleEvent(eventName, *args, **kwargs)

    Process an event with the state machine.

    This method looks up for an event handler in the current state and then in the `StateMachine` instance. Handler are looked up as ‘onEventName’ method. If a handler is found, it is called with the provided extra arguments, and this method returns the return value of the handler. If no handler is found, this method returns None.

    Parameters:

      eventName (str) – Name of the event to handle

    Returns:

      The return value of the handler or None

  validate()

    Called externally to validate the current interaction in case of a creation.

LEFT_BTN = 'left'

  Left mouse button.

RIGHT_BTN = 'right'

  Right mouse button.

MIDDLE_BTN = 'middle'

  Middle mouse button.

class ClickOrDrag(clickButtons=('left', 'right'), dragButtons=('left',))

  State machine for left and right click and left drag interaction.

  It is intended to be used through subclassing by overriding `click()`, `beginDrag()`, `drag()` and `endDrag()`.

  Parameters:

    - clickButtons (Set[str]) – Set of buttons that provides click interaction

    - dragButtons (Set[str]) – Set of buttons that provides drag interaction

  class Idle(machine)
  class Click(machine)
    enterState(x, y, btn)

      Called when the state machine enters this state.

      Arguments are those provided to the `goto()` method that triggered the transition to this state.

  class ClickOrDrag(machine)
    enterState(x, y, btn)

      Called when the state machine enters this state.

      Arguments are those provided to the `goto()` method that triggered the transition to this state.

  class Drag(machine)
    enterState(initPos, curPos, btn)

      Called when the state machine enters this state.

      Arguments are those provided to the `goto()` method that triggered the transition to this state.

  property clickButtons

    Buttons with click interaction (Set[int])

  property dragButtons

    Buttons with drag interaction (Set[int])

  click(x, y, btn)

    Called upon a button supporting click.

    Override in subclass.

    Parameters:

      - x (int) – X mouse position in pixels.

      - y (int) – Y mouse position in pixels.

      - btn (str) – The mouse button which was clicked.

  beginDrag(x, y, btn)

    Called at the beginning of a drag gesture with mouse button pressed.

    Override in subclass.

    Parameters:

      - x (int) – X mouse position in pixels.

      - y (int) – Y mouse position in pixels.

      - btn (str) – The mouse button for which a drag is starting.

  drag(x, y, btn)

    Called on mouse moved during a drag gesture.

    Override in subclass.

    Parameters:

      - x (int) – X mouse position in pixels.

      - y (int) – Y mouse position in pixels.

      - btn (str) – The mouse button for which a drag is in progress.

  endDrag(startPoint, endPoint, btn)

    Called at the end of a drag gesture when the mouse button is released.

    Override in subclass.

    Parameters:

      - startPoint (List[int]) – (x, y) mouse position in pixels at the beginning of the drag.

      - endPoint (List[int]) – (x, y) mouse position in pixels at the end of the drag.

      - btn (str) – The mouse button for which a drag is done.

## `LegendSelector`

Widget displaying curves legends and allowing to operate on curves.

This widget is meant to work with `PlotWindow`.

class LegendIcon(parent=None, curve=None)

  Object displaying a curve linestyle and symbol.

  Parameters:

    - parent (QWidget) – See `QWidget`

    - curve (Union[Curve,None]) – Curve with which to synchronize

  getCurve()

    Returns curve associated to this widget

    Return type:

      Union[Curve,None]

  setCurve(curve)

    Set the curve with which to synchronize this widget.

    Parameters:

      curve – Union[~silx.gui.plot.items.Curve,None]

class LegendModel(legendList=None, parent=None)

  Data model of curve legends.

  It holds the information of the curve:

  - color

  - line width

  - line style

  - visibility of the lines

  - symbol

  - visibility of the symbols

  rowCount(self, parent: QModelIndex = QModelIndex()) → int
  flags(self, index: QModelIndex) → Qt.ItemFlags
  data(self, index: QModelIndex, role: int = Qt.ItemDataRole.DisplayRole) → Any
  setData(self, index: QModelIndex, value: Any, role: int = Qt.ItemDataRole.EditRole) → bool
  insertLegendList(row, llist)
    Parameters:

      - row (int) – Determines after which row the items are inserted

      - llist (List) – Carries the new legend information

  insertRows(self, row: int, count: int, parent: QModelIndex = QModelIndex()) → bool
  removeRow(self, row: int, parent: QModelIndex = QModelIndex()) → bool
  removeRows(self, row: int, count: int, parent: QModelIndex = QModelIndex()) → bool
  setEditor(event, editor)
    Parameters:

      - event (str) – String that identifies the editor

      - editor (QWidget) – Widget used to change data in the underlying model

class LegendListItemWidget(parent=None, itemType=0)

  Object displaying a single item (i.e., a row) in the list.

  paint(painter, option, modelIndex)

    Here be docs..

    Parameters:

      - painter (QPainter)

      - option (QStyleOptionViewItem)

      - modelIndex (QModelIndex)

  editorEvent(self, event: QEvent | None, model: QAbstractItemModel | None, option: QStyleOptionViewItem, index: QModelIndex) → bool
  createEditor(self, parent: QWidget | None, option: QStyleOptionViewItem, index: QModelIndex) → QWidget | None
  sizeHint(self, option: QStyleOptionViewItem, index: QModelIndex) → QSize

class LegendListView(parent=None, model=None, contextMenu=None)

  Widget displaying a list of curve legends, line style and symbol.

  sigLegendSignal

    Signal emitting a dict when an action is triggered by the user.

  mousePressEvent(self, e: QMouseEvent | None)
  mouseDoubleClickEvent(self, e: QMouseEvent | None)
  mouseMoveEvent(self, e: QMouseEvent | None)
  mouseReleaseEvent(self, e: QMouseEvent | None)

class LegendListContextMenu(model)

  Contextual menu associated to items in a `LegendListView`.

  sigContextMenu

    Signal emitting a dict upon contextual menu actions.

  exec(self) → QAction | None
  exec(self, pos: QPoint, action: QAction | None = None) → QAction | None
  exec(actions: Iterable[QAction], pos: QPoint, at: QAction | None = None, parent: QWidget | None = None) → QAction | None
  exec_(self) → QAction | None
  exec_(self, p: QPoint, action: QAction | None = None) → QAction | None
  exec_(actions: Iterable[QAction], pos: QPoint, at: QAction | None = None, parent: QWidget | None = None) → QAction | None
  setActiveAction(self, act: QAction | None)

class RenameCurveDialog(parent=None, current='', curves=())

  Dialog box to input the name of a curve.

class LegendsDockWidget(parent=None, plot=None)

  QDockWidget with a `LegendSelector` connected to a PlotWindow.

  It makes the link between the LegendListView widget and the PlotWindow.

  Parameters:

    - parent – See `QDockWidget`

    - plot – `PlotWindow` instance on which to operate

  property plot

    The `PlotWindow` this widget is attached to.

  renameCurve(oldLegend, newLegend)

    Change the name of a curve using remove and addCurve

    Parameters:

      - oldLegend (str) – The legend of the curve to be changed

      - newLegend (str) – The new legend of the curve

  updateLegends(*args)

    Sync the LegendSelector widget displayed info with the plot.

## `_BaseMaskToolsWidget`

This module is a collection of base classes used in modules `MaskToolsWidget` (images) and `ScatterMaskToolsWidget`

class BaseMask(dataItem=None)

  Base class for `ImageMask` and `ScatterMask`

  A mask field with update operations.

  A mask is an array of the same shape as some underlying data. The mask array stores integer values in the range 0-255, to allow for 254 levels of mask (value 0 is reserved for unmasked data).

  The mask is updated using spatial selection methods: data located inside a selected area is masked with a specified mask level.

  sigChanged

    Signal emitted when the mask has changed

  sigStateChanged

    Signal emitted for each mask commit/undo/redo operation

  sigUndoable

    Signal emitted when undo becomes possible/impossible

  sigRedoable

    Signal emitted when redo becomes possible/impossible

  historyDepth

    Maximum number of operation stored in history list for undo

  setDataItem(item)

    Set a data item

    Parameters:

      item – A plot item, subclass of `silx.gui.plot.items.Item`

    Returns:

  getDataItem()

    Returns current plot item the mask is on.

    Return type:

      Union[Item,None]

  getDataValues()

    Return data values, as a numpy array with the same shape as the mask.

    This method must be implemented in a subclass, as the way of accessing data depends on the data item passed to `setDataItem()`

    Returns:

      Data values associated with the data item.

    Return type:

      numpy.ndarray

  getMask(copy=True)

    Get the current mask as a numpy array.

    Parameters:

      copy (bool) – True (default) to get a copy of the mask. If False, the returned array MUST not be modified.

    Returns:

      The array of the mask with dimension of the data to be masked.

    Return type:

      numpy.ndarray of uint8

  setMask(mask, copy=True)

    Set the mask to a new array.

    Parameters:

      - mask (numpy.ndarray of uint8, C-contiguous. Array of other types are converted.) – The array to use for the mask.

      - copy (bool) – True (the default) to copy the array, False to use it as is if possible.

  resetHistory()

    Reset history

  commit()

    Append the current mask to history if changed

  undo()

    Restore previous mask if any

  redo()

    Restore previously undone modification if any

  clear(level)

    Set all values of the given mask level to 0.

    Parameters:

      level (int) – Value of the mask to set to 0.

  invert(level)

    Invert mask of the given mask level.

    0 values become level and level values become 0.

    Parameters:

      level (int) – The level to invert.

  reset(shape=None)

    Reset the mask to zero and change its shape.

    Parameters:

      shape (tuple of int) – Shape of the new mask with the correct dimensionality with regards to the data dimensionality, or None to have an empty mask

  save(filename, kind)

    Save current mask in a file

    Parameters:

      - filename (str) – The file where to save to mask

      - kind (str) – The kind of file to save (e.g ‘npy’)

    Raises:

      Exception – Raised if the file writing fail

  updateStencil(level, stencil, mask=True)

    Mask/Unmask points from boolean mask: all elements that are True in the boolean mask are set to `level` (if `mask=True`) or 0 (if `mask=False`)

    Parameters:

      - level (int) – Mask level to update.

      - stencil (numpy.array of same dimension as the mask) – Boolean mask.

      - mask (bool) – True to mask (default), False to unmask.

  updateBelowThreshold(level, threshold, mask=True)

    Mask/unmask all points whose values are below a threshold.

    Parameters:

      - level (int)

      - threshold (float) – Threshold

      - mask (bool) – True to mask (default), False to unmask.

  updateBetweenThresholds(level, min_, max_, mask=True)

    Mask/unmask all points whose values are in a range.

    Parameters:

      - level (int)

      - min (float) – Lower threshold

      - max (float) – Upper threshold

      - mask (bool) – True to mask (default), False to unmask.

  updateAboveThreshold(level, threshold, mask=True)

    Mask/unmask all points whose values are above a threshold.

    Parameters:

      - level (int) – Mask level to update.

      - threshold (float) – Threshold.

      - mask (bool) – True to mask (default), False to unmask.

  updateNotFinite(level, mask=True)

    Mask/unmask all points whose values are not finite.

    Parameters:

      - level (int) – Mask level to update.

      - mask (bool) – True to mask (default), False to unmask.

  updateRectangle(level, row, col, height, width, mask=True)

    Mask/Unmask data inside a rectangle, with the given mask level.

    Parameters:

      - level (int) – Mask level to update, in range 1-255.

      - row – Starting row/y of the rectangle

      - col – Starting column/x of the rectangle

      - height

      - width

      - mask (bool) – True to mask (default), False to unmask.

  updatePolygon(level, vertices, mask=True)

    Mask/Unmask data inside a polygon, with the given mask level.

    Parameters:

      - level (int) – Mask level to update.

      - vertices – Nx2 array of polygon corners as (row, col) / (y, x)

      - mask (bool) – True to mask (default), False to unmask.

  updatePoints(level, rows, cols, mask=True)

    Mask/Unmask points with given coordinates.

    Parameters:

      - level (int) – Mask level to update.

      - rows (1D numpy.ndarray) – Rows/ordinates (y) of selected points

      - cols (1D numpy.ndarray) – Columns/abscissa (x) of selected points

      - mask (bool) – True to mask (default), False to unmask.

  updateDisk(level, crow, ccol, radius, mask=True)

    Mask/Unmask data located inside a dick of the given mask level.

    Parameters:

      - level (int) – Mask level to update.

      - crow – Disk center row/ordinate (y).

      - ccol – Disk center column/abscissa.

      - radius (float) – Radius of the disk in mask array unit

      - mask (bool) – True to mask (default), False to unmask.

  updateEllipse(level, crow, ccol, radius_r, radius_c, mask=True)

    Mask/Unmask a disk of the given mask level.

    Parameters:

      - level (int) – Mask level to update.

      - crow (int) – Row of the center of the ellipse

      - ccol (int) – Column of the center of the ellipse

      - radius_r (float) – Radius of the ellipse in the row

      - radius_c (float) – Radius of the ellipse in the column

      - mask (bool) – True to mask (default), False to unmask.

  updateLine(level, row0, col0, row1, col1, width, mask=True)

    Mask/Unmask a line of the given mask level.

    Parameters:

      - level (int) – Mask level to update.

      - row0 – Row/y of the starting point.

      - col0 – Column/x of the starting point.

      - row1 – Row/y of the end point.

      - col1 – Column/x of the end point.

      - width – Width of the line in mask array unit.

      - mask (bool) – True to mask (default), False to unmask.

class BaseMaskToolsWidget(parent=None, plot=None, mask=None)

  Base class for `MaskToolsWidget` (image mask) and `scatterMaskToolsWidget`

  getMaskedItem()

    Returns the item that is currently being masked

    Return type:

      Union[Item,None]

  getSelectionMask(copy=True)

    Get the current mask as a numpy array.

    Parameters:

      copy (bool) – True (default) to get a copy of the mask. If False, the returned array MUST not be modified.

    Returns:

      The mask (as an array of uint8) with dimension of the ‘active’ plot item. If there is no active image or scatter, it returns None.

    Return type:

      Union[numpy.ndarray,None]

  setSelectionMask(mask)

    Set the mask: Must be implemented in subclass

  resetSelectionMask()

    Reset the mask: Must be implemented in subclass

  multipleMasks()

    Return the current mode of multiple masks support.

    See `setMultipleMasks()`

  setMultipleMasks(mode)

    Set the mode of multiple masks support.

    Available modes:

    - ‘single’: Edit a single level of mask

    - ‘exclusive’: Supports to 256 levels of non overlapping masks

    Parameters:

      mode (str) – The mode to use

  setMaskFileDirectory(path)

    Set the default directory to use by load/save GUI tools

    The directory is also updated by the user, if he change the location of the dialog.

  getMaskFileDirectory()

    Get the default directory used by load/save GUI tools

  property maskFileDir

    The directory from which to load/save mask from/to files.

  property plot

    The `PlotWindow` this widget is attached to.

  setDirection(direction=0)

    Set the direction of the layout of the widget

    Parameters:

      direction – QBoxLayout direction

  isMaskInteractionActivated()

    Returns true if any mask interaction is activated

  changeEvent(event)

    Reset drawing action when disabling widget

  save(filename, kind)

    Save current mask in a file

    Parameters:

      - filename (str) – The file where to save to mask

      - kind (str) – The kind of file to save in ‘edf’, ‘tif’, ‘npy’

    Raises:

      Exception – Raised if the process fails

  getCurrentMaskColor()

    Returns the color of the current selected level.

    Return type:

      A tuple or a python array

  resetMaskColors(level=None)

    Reset the mask color at the given level to be defaultColors

    Parameters:

      level – The index of the mask for which we want to reset the color. If none we will reset color for all masks.

  setMaskColors(rgb, level=None)

    Set the masks color

    Parameters:

      - rgb – The rgb color

      - level – The index of the mask for which we want to change the color. If none set this color for all the masks

  getMaskColors()

    masks colors getter

class BaseMaskToolsDockWidget(parent=None, name='Mask', widget=None)

  Base class for `MaskToolsWidget` and `ScatterMaskToolsWidget`.

  For integration in a `PlotWindow`.

  Parameters:

    parent – See `QDockWidget`

  Paran str name:

    The title of this widget

  getSelectionMask(copy=True)

    Get the current mask as a 2D array.

    Parameters:

      copy (bool) – True (default) to get a copy of the mask. If False, the returned array MUST not be modified.

    Returns:

      The array of the mask with dimension of the ‘active’ image. If there is no active image, an empty array is returned.

    Return type:

      2D numpy.ndarray of uint8

  setSelectionMask(mask, copy=True)

    Set the mask to a new array.

    Parameters:

      - mask (numpy.ndarray of uint8 of dimension 2, C-contiguous. Array of other types are converted.) – The array to use for the mask.

      - copy (bool) – True (the default) to copy the array, False to use it as is if possible.

    Returns:

      None if failed, shape of mask as 2-tuple if successful. The mask can be cropped or padded to fit active image, the returned shape is that of the active image.

  resetSelectionMask()

    Reset the mask to an array of zeros with the shape of the current data.

  toggleViewAction()

    Returns a checkable action that shows or closes this widget.

    See `QMainWindow`.

## `MaskToolsWidget`

Widget providing a set of tools to draw masks on a PlotWidget.

This widget is meant to work with `silx.gui.plot.PlotWidget`.

- `ImageMask`: Handle mask bitmap update and history

- `MaskToolsWidget`: GUI for `Mask`

- `MaskToolsDockWidget`: DockWidget to integrate in `PlotWindow`

class ImageMask(image=None)

  Bases: `BaseMask`

  A 2D mask field with update operations.

  Coords follows (row, column) convention and are in mask array coords.

  This is meant for internal use by `MaskToolsWidget`.

  getDataValues()

    Return image data as a 2D or 3D array (if it is a RGBA image).

    Return type:

      2D or 3D numpy.ndarray

  save(filename, kind)

    Save current mask in a file

    Parameters:

      - filename (str) – The file where to save to mask

      - kind (str) – The kind of file to save in ‘edf’, ‘tif’, ‘npy’, ‘h5’ or ‘msk’ (if FabIO is installed)

    Raises:

      Exception – Raised if the file writing fail

  updateRectangle(level, row, col, height, width, mask=True)

    Mask/Unmask a rectangle of the given mask level.

    Parameters:

      - level (int) – Mask level to update.

      - row (int) – Starting row of the rectangle

      - col (int) – Starting column of the rectangle

      - height (int)

      - width (int)

      - mask (bool) – True to mask (default), False to unmask.

  updatePolygon(level, vertices, mask=True)

    Mask/Unmask a polygon of the given mask level.

    Parameters:

      - level (int) – Mask level to update.

      - vertices – Nx2 array of polygon corners as (row, col)

      - mask (bool) – True to mask (default), False to unmask.

  updatePoints(level, rows, cols, mask=True)

    Mask/Unmask points with given coordinates.

    Parameters:

      - level (int) – Mask level to update.

      - rows (1D numpy.ndarray) – Rows of selected points

      - cols (1D numpy.ndarray) – Columns of selected points

      - mask (bool) – True to mask (default), False to unmask.

  updateDisk(level, crow, ccol, radius, mask=True)

    Mask/Unmask a disk of the given mask level.

    Parameters:

      - level (int) – Mask level to update.

      - crow (int) – Disk center row.

      - ccol (int) – Disk center column.

      - radius (float) – Radius of the disk in mask array unit

      - mask (bool) – True to mask (default), False to unmask.

  updateEllipse(level, crow, ccol, radius_r, radius_c, mask=True)

    Mask/Unmask an ellipse of the given mask level.

    Parameters:

      - level (int) – Mask level to update.

      - crow (int) – Row of the center of the ellipse

      - ccol (int) – Column of the center of the ellipse

      - radius_r (float) – Radius of the ellipse in the row

      - radius_c (float) – Radius of the ellipse in the column

      - mask (bool) – True to mask (default), False to unmask.

  updateLine(level, row0, col0, row1, col1, width, mask=True)

    Mask/Unmask a line of the given mask level.

    Parameters:

      - level (int) – Mask level to update.

      - row0 (int) – Row of the starting point.

      - col0 (int) – Column of the starting point.

      - row1 (int) – Row of the end point.

      - col1 (int) – Column of the end point.

      - width (int) – Width of the line in mask array unit.

      - mask (bool) – True to mask (default), False to unmask.

class MaskToolsWidget(parent=None, plot=None)

  Bases: `BaseMaskToolsWidget`

  Widget with tools for drawing mask on an image in a PlotWidget.

  setItemMaskUpdated(enabled)

    Toggle item mask and mask tool synchronisation.

    Parameters:

      - enabled (`bool`) – True to synchronise. Default: False

      - enabled

    Return type:

      `None`

  isItemMaskUpdated()

    Returns whether or not item and mask tool masks are synchronised.

    Return type:

      bool

  setSelectionMask(mask, copy=True)

    Set the mask to a new array.

    Parameters:

      - mask (numpy.ndarray of uint8 of dimension 2, C-contiguous. Array of other types are converted.) – The array to use for the mask or None to reset the mask.

      - copy (bool) – True (the default) to copy the array, False to use it as is if possible.

    Returns:

      None if failed, shape of mask as 2-tuple if successful. The mask can be cropped or padded to fit active image, the returned shape is that of the active image.

  showEvent(self, a0: QShowEvent | None)
  hideEvent(self, a0: QHideEvent | None)
  load(filename)

    Load a mask from an image file.

    Parameters:

      filename (str) – File name from which to load the mask

    Raises:

      - Exception – An exception in case of failure

      - RuntimeWarning – In case the mask was applied but with some import changes to notice

  resetSelectionMask()

    Reset the mask

class MaskToolsDockWidget(parent=None, plot=None, name='Mask')

  Bases: `BaseMaskToolsDockWidget`

  `MaskToolsWidget` embedded in a QDockWidget.

  For integration in a `PlotWindow`.

  Parameters:

    - parent – See `QDockWidget`

    - plot – The PlotWidget this widget is operating on

  Paran str name:

    The title of this widget

## `ScatterMaskToolsWidget`

Widget providing a set of tools to draw masks on a PlotWidget.

This widget is meant to work with a modified `silx.gui.plot.PlotWidget`

- `ScatterMask`: Handle scatter mask update and history

- `ScatterMaskToolsWidget`: GUI for `ScatterMask`

- `ScatterMaskToolsDockWidget`: DockWidget to integrate in `PlotWindow`

class ScatterMask(scatter=None)

  Bases: `BaseMask`

  A 1D mask for scatter data.

  getDataValues()

    Return scatter data values as a 1D array.

    Return type:

      1D numpy.ndarray

  save(filename, kind)

    Save current mask in a file

    Parameters:

      - filename (str) – The file where to save to mask

      - kind (str) – The kind of file to save (e.g ‘npy’)

    Raises:

      Exception – Raised if the file writing fail

  updatePoints(level, indices, mask=True)

    Mask/Unmask points with given indices.

    Parameters:

      - level (int) – Mask level to update.

      - indices – Sequence or 1D array of indices of points to be updated

      - mask (bool) – True to mask (default), False to unmask.

  updatePolygon(level, vertices, mask=True)

    Mask/Unmask a polygon of the given mask level.

    Parameters:

      - level (int) – Mask level to update.

      - vertices – Nx2 array of polygon corners as (y, x) or (row, col)

      - mask (bool) – True to mask (default), False to unmask.

  updateRectangle(level, y, x, height, width, mask=True)

    Mask/Unmask data inside a rectangle

    Parameters:

      - level (int) – Mask level to update.

      - y (float) – Y coordinate of bottom left corner of the rectangle

      - x (float) – X coordinate of bottom left corner of the rectangle

      - height (float)

      - width (float)

      - mask (bool) – True to mask (default), False to unmask.

  updateDisk(level, cy, cx, radius, mask=True)

    Mask/Unmask a disk of the given mask level.

    Parameters:

      - level (int) – Mask level to update.

      - cy (float) – Disk center (y).

      - cx (float) – Disk center (x).

      - radius (float) – Radius of the disk in mask array unit

      - mask (bool) – True to mask (default), False to unmask.

  updateEllipse(level, crow, ccol, radius_r, radius_c, mask=True)

    Mask/Unmask an ellipse of the given mask level.

    Parameters:

      - level (int) – Mask level to update.

      - crow (int) – Row of the center of the ellipse

      - ccol (int) – Column of the center of the ellipse

      - radius_r (float) – Radius of the ellipse in the row

      - radius_c (float) – Radius of the ellipse in the column

      - mask (bool) – True to mask (default), False to unmask.

  updateLine(level, y0, x0, y1, x1, width, mask=True)

    Mask/Unmask points inside a rectangle defined by a line (two end points) and a width.

    Parameters:

      - level (int) – Mask level to update.

      - y0 (float) – Row of the starting point.

      - x0 (float) – Column of the starting point.

      - row1 (float) – Row of the end point.

      - col1 (float) – Column of the end point.

      - width (float) – Width of the line.

      - mask (bool) – True to mask (default), False to unmask.

class ScatterMaskToolsWidget(parent=None, plot=None)

  Bases: `BaseMaskToolsWidget`

  Widget with tools for masking data points on a scatter in a `PlotWidget`.

  setSelectionMask(mask, copy=True)

    Set the mask to a new array.

    Parameters:

      - mask (numpy.ndarray of uint8, C-contiguous. Array of other types are converted.) – The array to use for the mask or None to reset the mask.

      - copy (bool) – True (the default) to copy the array, False to use it as is if possible.

    Returns:

      None if failed, shape of mask as 1-tuple if successful. The mask can be cropped or padded to fit active scatter, the returned shape is that of the scatter data.

  showEvent(self, a0: QShowEvent | None)
  hideEvent(self, a0: QHideEvent | None)
  load(filename)

    Load a mask from an image file.

    Parameters:

      filename (str) – File name from which to load the mask

    Raises:

      - Exception – An exception in case of failure

      - RuntimeWarning – In case the mask was applied but with some import changes to notice

  resetSelectionMask()

    Reset the mask

class ScatterMaskToolsDockWidget(parent=None, plot=None, name='Mask')

  Bases: `BaseMaskToolsDockWidget`

  `ScatterMaskToolsWidget` embedded in a QDockWidget.

  For integration in a `PlotWindow`.

  Parameters:

    - parent – See `QDockWidget`

    - plot – The PlotWidget this widget is operating on

  Paran str name:

    The title of this widget

## `PlotEvents`

Functions to prepare events to be sent to Plot callback.

prepareDrawingSignal(event, type_, points, parameters=None)

  See Plot documentation for content of events

prepareMouseSignal(eventType, button, xData, yData, xPixel, yPixel)

  See Plot documentation for content of events

prepareHoverSignal(label, type_, posData, posPixel, draggable, selectable)

  See Plot documentation for content of events

prepareMarkerSignal(eventType, button, label, type_, draggable, selectable, posDataMarker, posPixelCursor=None, posDataCursor=None)

  See Plot documentation for content of events

prepareImageSignal(button, item, col, row, x, y, xPixel, yPixel)

  See Plot documentation for content of events

prepareCurveSignal(button, item, xData, yData, x, y, xPixel, yPixel)

  See Plot documentation for content of events

prepareLimitsChangedSignal(sourceObj, xRange, yRange, y2Range)

  See Plot documentation for content of events

## `PlotInteraction`

Implementation of the interaction for the `Plot`.

class Pan(plot, **kwargs)

  Pan plot content and zoom on wheel state machine.

  beginDrag(x, y, btn)

    Called at the beginning of a drag gesture with mouse button pressed.

    Override in subclass.

    Parameters:

      - x (int) – X mouse position in pixels.

      - y (int) – Y mouse position in pixels.

      - btn (str) – The mouse button for which a drag is starting.

  drag(x, y, btn)

    Called on mouse moved during a drag gesture.

    Override in subclass.

    Parameters:

      - x (int) – X mouse position in pixels.

      - y (int) – Y mouse position in pixels.

      - btn (str) – The mouse button for which a drag is in progress.

  endDrag(startPos, endPos, btn)

    Called at the end of a drag gesture when the mouse button is released.

    Override in subclass.

    Parameters:

      - startPoint (List[int]) – (x, y) mouse position in pixels at the beginning of the drag.

      - endPoint (List[int]) – (x, y) mouse position in pixels at the end of the drag.

      - btn (str) – The mouse button for which a drag is done.

class AxesExtent(xmin, xmax, ymin, ymax, y2min, y2max)
  xmin: `float`

    Alias for field number 0

  xmax: `float`

    Alias for field number 1

  ymin: `float`

    Alias for field number 2

  ymax: `float`

    Alias for field number 3

  y2min: `float`

    Alias for field number 4

  y2max: `float`

    Alias for field number 5

class Zoom(plot, color)

  Zoom-in/out state machine.

  Zoom-in on selected area, zoom-out on right click, and zoom on mouse wheel.

  beginDrag(x, y, btn)

    Called at the beginning of a drag gesture with mouse button pressed.

    Override in subclass.

    Parameters:

      - x (int) – X mouse position in pixels.

      - y (int) – Y mouse position in pixels.

      - btn (str) – The mouse button for which a drag is starting.

  drag(x1, y1, btn)

    Called on mouse moved during a drag gesture.

    Override in subclass.

    Parameters:

      - x (int) – X mouse position in pixels.

      - y (int) – Y mouse position in pixels.

      - btn (str) – The mouse button for which a drag is in progress.

  endDrag(startPos, endPos, btn)

    Called at the end of a drag gesture when the mouse button is released.

    Override in subclass.

    Parameters:

      - startPoint (List[int]) – (x, y) mouse position in pixels at the beginning of the drag.

      - endPoint (List[int]) – (x, y) mouse position in pixels at the end of the drag.

      - btn (str) – The mouse button for which a drag is done.

class Select(plot, parameters, states, state)

  Base class for drawing selection areas.

class SelectPolygon(plot, parameters)

  Drawing selection polygon area state machine.

  class Idle(machine)
  class Select(machine)
    enterState(x, y)

      Called when the state machine enters this state.

      Arguments are those provided to the `goto()` method that triggered the transition to this state.

    updateFirstPoint()

      Update drawing first point, using self._firstPos

    updateSelectionArea()

      Update drawing selection area using self.points

    validate()

      Called externally to validate the current interaction in case of a creation.

  getDragThreshold()

    Return dragging ratio with device to pixel ratio applied.

    Return type:

      float

class Select2Points(plot, parameters)

  Base class for drawing selection based on 2 input points.

  class Idle(machine)
  class Start(machine)
    enterState(x, y)

      Called when the state machine enters this state.

      Arguments are those provided to the `goto()` method that triggered the transition to this state.

  class Select(machine)
    enterState(x, y)

      Called when the state machine enters this state.

      Arguments are those provided to the `goto()` method that triggered the transition to this state.

class SelectEllipse(plot, parameters)

  Drawing ellipse selection area state machine.

class SelectRectangle(plot, parameters)

  Drawing rectangle selection area state machine.

class SelectLine(plot, parameters)

  Drawing line selection area state machine.

class Select1Point(plot, parameters)

  Base class for drawing selection area based on one input point.

  class Idle(machine)
  class Select(machine)
    enterState(x, y)

      Called when the state machine enters this state.

      Arguments are those provided to the `goto()` method that triggered the transition to this state.

class SelectHLine(plot, parameters)

  Drawing a horizontal line selection area state machine.

class SelectVLine(plot, parameters)

  Drawing a vertical line selection area state machine.

class DrawFreeHand(plot, parameters)

  Interaction for drawing pencil. It display the preview of the pencil before pressing the mouse.

  class Idle(machine)
  class Select(machine)
    enterState(x, y)

      Called when the state machine enters this state.

      Arguments are those provided to the `goto()` method that triggered the transition to this state.

class SelectFreeLine(plot, parameters)

  Base class for drawing free lines with tools such as pencil.

  click(x, y, btn)

    Called upon a button supporting click.

    Override in subclass.

    Parameters:

      - x (int) – X mouse position in pixels.

      - y (int) – Y mouse position in pixels.

      - btn (str) – The mouse button which was clicked.

  beginDrag(x, y, btn)

    Called at the beginning of a drag gesture with mouse button pressed.

    Override in subclass.

    Parameters:

      - x (int) – X mouse position in pixels.

      - y (int) – Y mouse position in pixels.

      - btn (str) – The mouse button for which a drag is starting.

  drag(x, y, btn)

    Called on mouse moved during a drag gesture.

    Override in subclass.

    Parameters:

      - x (int) – X mouse position in pixels.

      - y (int) – Y mouse position in pixels.

      - btn (str) – The mouse button for which a drag is in progress.

  endDrag(startPos, endPos, btn)

    Called at the end of a drag gesture when the mouse button is released.

    Override in subclass.

    Parameters:

      - startPoint (List[int]) – (x, y) mouse position in pixels at the beginning of the drag.

      - endPoint (List[int]) – (x, y) mouse position in pixels at the end of the drag.

      - btn (str) – The mouse button for which a drag is done.

class ItemsInteraction(plot)

  Interaction with items (markers, curves and images).

  This class provides selection and dragging of plot primitives that support those interaction. It is also meant to be combined with the zoom interaction.

  class Idle(*args, **kw)
    enterState()

      Called when the state machine enters this state.

      Arguments are those provided to the `goto()` method that triggered the transition to this state.

  click(x, y, btn)

    Handle mouse click

    Parameters:

      - x – X position of the mouse in pixels

      - y – Y position of the mouse in pixels

      - btn – Pressed button id

    Returns:

      True if click is catched by an item, False otherwise

  beginDrag(x, y, btn)

    Handle begining of drag interaction

    Parameters:

      - x – X position of the mouse in pixels

      - y – Y position of the mouse in pixels

      - btn (str) – The mouse button for which a drag is starting.

    Returns:

      True if drag is catched by an item, False otherwise

  drag(x, y, btn)

    Called on mouse moved during a drag gesture.

    Override in subclass.

    Parameters:

      - x (int) – X mouse position in pixels.

      - y (int) – Y mouse position in pixels.

      - btn (str) – The mouse button for which a drag is in progress.

  endDrag(startPos, endPos, btn)

    Called at the end of a drag gesture when the mouse button is released.

    Override in subclass.

    Parameters:

      - startPoint (List[int]) – (x, y) mouse position in pixels at the beginning of the drag.

      - endPoint (List[int]) – (x, y) mouse position in pixels at the end of the drag.

      - btn (str) – The mouse button for which a drag is done.

class ItemsInteractionForCombo(plot)

  Interaction with items to combine through `FocusManager`.

  class Idle(*args, **kw)

class FocusManager(eventHandlers=())

  Manages focus across multiple event handlers

  On press an event handler can acquire focus. By default it looses focus when all buttons are released.

  class Idle(machine)
  class Focus(machine)
    enterState(eventHandler, btn)

      Called when the state machine enters this state.

      Arguments are those provided to the `goto()` method that triggered the transition to this state.

    validate()

      Called externally to validate the current interaction in case of a creation.

class ZoomAndSelect(plot, color)

  Combine Zoom and ItemInteraction state machine.

  Parameters:

    - plot – The Plot to which this interaction is attached

    - color – The color to use for the zoom area bounding box

  property color

    Color of the zoom area

  property zoomEnabledAxes: EnabledAxes

    Whether or not to apply zoom for each axis

  click(x, y, btn)

    Handle mouse click

    Parameters:

      - x – X position of the mouse in pixels

      - y – Y position of the mouse in pixels

      - btn – Pressed button id

    Returns:

      True if click is catched by an item, False otherwise

  beginDrag(x, y, btn)

    Handle start drag and switching between zoom and item drag.

    Parameters:

      - x – X position in pixels

      - y – Y position in pixels

      - btn (str) – The mouse button for which a drag is starting.

  drag(x, y, btn)

    Handle drag, eventually forwarding to zoom.

    Parameters:

      - x – X position in pixels

      - y – Y position in pixels

      - btn (str) – The mouse button for which a drag is in progress.

  endDrag(startPos, endPos, btn)

    Handle end of drag, eventually forwarding to zoom.

    Parameters:

      - startPos – (x, y) position at the beginning of the drag

      - endPos – (x, y) position at the end of the drag

      - btn (str) – The mouse button for which a drag is done.

class PanAndSelect(plot)

  Combine Pan and ItemInteraction state machine.

  Parameters:

    plot – The Plot to which this interaction is attached

  click(x, y, btn)

    Handle mouse click

    Parameters:

      - x – X position of the mouse in pixels

      - y – Y position of the mouse in pixels

      - btn – Pressed button id

    Returns:

      True if click is catched by an item, False otherwise

  beginDrag(x, y, btn)

    Handle start drag and switching between zoom and item drag.

    Parameters:

      - x – X position in pixels

      - y – Y position in pixels

      - btn (str) – The mouse button for which a drag is starting.

  drag(x, y, btn)

    Handle drag, eventually forwarding to zoom.

    Parameters:

      - x – X position in pixels

      - y – Y position in pixels

      - btn (str) – The mouse button for which a drag is in progress.

  endDrag(startPos, endPos, btn)

    Handle end of drag, eventually forwarding to zoom.

    Parameters:

      - startPos – (x, y) position at the beginning of the drag

      - endPos – (x, y) position at the end of the drag

      - btn (str) – The mouse button for which a drag is done.

class DrawMode(plot, shape, label, color, width)

  Interactive mode for draw and select

  getDescription()

    Returns the dict describing this interactive mode

class DrawSelectMode(plot, shape, label, color, width)

  Interactive mode for draw and select

  handleEvent(eventName, *args, **kwargs)

    Process an event with the state machine.

    This method looks up for an event handler in the current state and then in the `StateMachine` instance. Handler are looked up as ‘onEventName’ method. If a handler is found, it is called with the provided extra arguments, and this method returns the return value of the handler. If no handler is found, this method returns None.

    Parameters:

      eventName (str) – Name of the event to handle

    Returns:

      The return value of the handler or None

  getDescription()

    Returns the dict describing this interactive mode

class PlotInteraction(parent)

  PlotWidget user interaction handler.

  Parameters:

    plot – The `PlotWidget` to apply interaction to

  sigChanged

    Signal emitted when the interaction configuration has changed

  isZoomOnWheelEnabled()

    Returns whether or not wheel interaction triggers zoom

    Return type:

      `bool`

  setZoomOnWheelEnabled(enabled)

    Toggle zoom on wheel interaction

    Parameters:

      enabled (`bool`)

  setZoomEnabledAxes(xaxis, yaxis, y2axis)

    Toggle zoom interaction for each axis

    This is taken into account only if the plot does not keep aspect ratio.

    Parameters:

      - xaxis (`bool`)

      - yaxis (`bool`)

      - y2axis (`bool`)

  getZoomEnabledAxes()

    Returns axes for which zoom is enabled

    Return type:

      `EnabledAxes`

  handleEvent(event, *args, **kwargs)

    Forward event to current interactive mode state machine.

## `_utils`

Miscellaneous utility functions for the Plot

addMarginsToLimits(margins, isXLog, isYLog, xMin, xMax, yMin, yMax, y2Min=None, y2Max=None)

  Returns updated limits by extending them with margins.

  Parameters:

    margins (A 4-tuple of floats as (xMinMargin, xMaxMargin, yMinMargin, yMaxMargin)) – The ratio of the margins to add or None for no margins.

  Returns:

    The updated limits

  Return type:

    tuple of 4 or 6 floats: Either (xMin, xMax, yMin, yMax) or (xMin, xMax, yMin, yMax, y2Min, y2Max) if y2Min and y2Max are provided.

### `ticklayout`

This module implements labels layout on graph axes.

numberOfDigits(tickSpacing)

  Returns the number of digits to display for text label.

  Parameters:

    tickSpacing (float) – Step between ticks in data space.

  Returns:

    Number of digits to show for labels.

  Return type:

    int

niceNumGeneric(value, niceFractions=None, isRound=False)

  A more generic implementation of the _niceNum function

  Allows the user to specify the fractions instead of using a hardcoded list of [1, 2, 5, 10.0].

niceNumbers(vMin, vMax, nTicks=5)

  Returns tick positions.

  This function implements graph labels layout using nice numbers by Paul Heckbert from “Graphics Gems”, Academic Press, 1990. See C code.

  Parameters:

    - vMin (float) – The min value on the axis

    - vMax (float) – The max value on the axis

    - nTicks (int) – The number of ticks to position

  Returns:

    min, max, increment value of tick positions and number of fractional digit to show

  Return type:

    tuple

ticks(vMin, vMax, nbTicks=5)

  Returns tick positions and labels using nice numbers algorithm.

  This enforces ticks to be within [vMin, vMax] range. It returns at least 1 tick (when vMin == vMax).

  Parameters:

    - vMin (float) – The min value on the axis

    - vMax (float) – The max value on the axis

    - nbTicks (int) – The number of ticks to position

  Returns:

    tick positions and corresponding text labels

  Return type:

    2-tuple: list of float, list of string

niceNumbersAdaptative(vMin, vMax, axisLength, tickDensity)

  Returns tick positions using `niceNumbers()` and a density of ticks.

  axisLength and tickDensity are based on the same unit (e.g., pixel).

  Parameters:

    - vMin (float) – The min value on the axis

    - vMax (float) – The max value on the axis

    - axisLength (float) – The length of the axis.

    - tickDensity (float) – The density of ticks along the axis.

  Returns:

    min, max, increment value of tick positions and number of fractional digit to show

  Return type:

    tuple

niceNumbersForLog10(minLog, maxLog, nTicks=5)

  Return tick positions for logarithmic scale

  Parameters:

    - minLog (float) – log10 of the min value on the axis

    - maxLog (float) – log10 of the max value on the axis

    - nTicks (int) – The number of ticks to position

  Returns:

    log10 of min, max, increment value of tick positions and number of fractional digit to show

  Return type:

    tuple of int

niceNumbersAdaptativeForLog10(vMin, vMax, axisLength, tickDensity)

  Returns tick positions using `niceNumbers()` and a density of ticks.

  axisLength and tickDensity are based on the same unit (e.g., pixel).

  Parameters:

    - vMin (float) – The min value on the axis

    - vMax (float) – The max value on the axis

    - axisLength (float) – The length of the axis.

    - tickDensity (float) – The density of ticks along the axis.

  Returns:

    log10 of min, max, increment value of tick positions and number of fractional digit to show

  Return type:

    tuple

computeLogSubTicks(ticks, lowBound, highBound)

  Return the sub ticks for the log scale for all given ticks if subtick is in [lowBound, highBound]

  Parameters:

    - ticks – log10 of the ticks

    - lowBound – the lower boundary of ticks

    - highBound – the higher boundary of ticks

  Returns:

    all the sub ticks contained in ticks (log10)