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:

The widgets also use the following miscellaneous modules:

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. It uses backends.ModestImage to provide a faster matplotlib AxesImage class using nearest values. The backends.BackendMatplotlib the provides two classes:

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.

Plot and backend

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 silx.gui.plot.backends.BackendBase.BackendBase(plot, parent=None)[source]

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

contextMenuEvent(event)[source]

Override QWidget.contextMenuEvent to implement the context menu

addCurve(x, y, legend, color, symbol, linewidth, linestyle, yaxis, xerror, yerror, z, selectable, fill, alpha, symbolsize)[source]

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
  • legend (str) – The legend to be associated to the curve
  • 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
  • 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 (str) –

    Type of line:

    - ' ' or ''  no line
    - '-'  solid line
    - '--' dashed line
    - '-.' dash-dot line
    - ':'  dotted line
    
  • 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
  • z (int) – Layer on which to draw the cuve
  • selectable (bool) – indicate if the curve can be selected
  • 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, legend, origin, scale, z, selectable, draggable, colormap, alpha)[source]

Add an image to the plot.

Parameters:
  • data (numpy.ndarray) – (nrows, ncolumns) data or (nrows, ncolumns, RGBA) ubyte array
  • legend (str) – The legend to be associated to the image
  • 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.)
  • z (int) – Layer on which to draw the image
  • selectable (bool) – indicate if the image can be selected
  • draggable (bool) – indicate if the image can be moved
  • colormap (Colormap) – Colormap describing the colormap 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

addItem(x, y, legend, shape, color, fill, overlay, z)[source]

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
  • legend (str) – The legend to be associated to the item
  • 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
  • z (int) – Layer on which to draw the item
Returns:

The handle used by the backend to univocally access the item

addMarker(x, y, legend, text, color, selectable, draggable, symbol, constraint)[source]

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

Parameters:
  • x (float) – Horizontal position of the marker in graph coordinates. If None, the marker is a horizontal line.
  • y (float) – Vertical position of the marker in graph coordinates. If None, the marker is a vertical line.
  • legend (str) – Legend associated to the marker
  • text (str) – Text associated to the marker (or None for no text)
  • color (str) – Color to be used for instance ‘blue’, ‘b’, ‘#FF0000’
  • selectable (bool) – indicate if the marker can be selected
  • draggable (bool) – indicate if the marker can be moved
  • symbol (str) –

    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
  • constraint (None or a callable that takes the coordinates of the current cursor position in the plot as input and that returns the filtered coordinates.) – A function filtering marker displacement by dragging operations or None for no filter. This function is called each time a marker is moved. This parameter is only used if draggable is True.
Returns:

Handle used by the backend to univocally access the marker

remove(item)[source]

Remove an existing item from the plot.

Parameters:item – A backend specific item handle returned by a add* method
setGraphCursorShape(cursor)[source]

Set the cursor shape.

To override in interactive backends.

Parameters:cursor (str) – Name of the cursor shape or None
setGraphCursor(flag, color, linewidth, linestyle)[source]

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 or one of the predefined styles.) –

    Type of line:

    - ' ' no line
    - '-' solid line
    - '--' dashed line
    - '-.' dash-dot line
    - ':' dotted line
    
pickItems(x, y, kinds)[source]

Get a list of items at a pixel position.

Parameters:
  • x (float) – The x pixel coord where to pick.
  • y (float) – The y pixel coord where to pick.
  • kind (List[str]) – List of item kinds to pick. Supported kinds: ‘marker’, ‘curve’, ‘image’.
Returns:

All picked items from back to front. One dict per item, with ‘kind’ key in ‘curve’, ‘marker’, ‘image’; ‘legend’ key, the item legend. and for curves, ‘xdata’ and ‘ydata’ keys storing picked position on the curve.

Return type:

list of dict

setCurveColor(curve, color)[source]

Set the color of a curve.

Parameters:
  • curve – The curve handle
  • color (str) – The color to use.
getWidgetHandle()[source]

Return the widget this backend is drawing to.

postRedisplay()[source]

Trigger a Plot.replot().

Default implementation triggers a synchronous replot if plot is dirty. This method should be overridden by the embedding widget in order to provide an asynchronous call to replot in order to optimize the number replot operations.

replot()[source]

Redraw the plot.

saveGraph(fileName, fileFormat, dpi)[source]

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)[source]

Set the main title of the plot.

Parameters:title (str) – Title associated to the plot
setGraphXLabel(label)[source]

Set the X axis label.

Parameters:label (str) – label associated to the plot bottom X axis
setGraphYLabel(label, axis)[source]

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)[source]

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()[source]

Get the graph X (bottom) limits.

Returns:Minimum and maximum values of the X axis
setGraphXLimits(xmin, xmax)[source]

Set the limits of X axis.

Parameters:
  • xmin (float) – minimum bottom axis value
  • xmax (float) – maximum bottom axis value
getGraphYLimits(axis)[source]

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)[source]

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()[source]

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)[source]

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()[source]

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

Return type:bool
setXAxisTimeSeries(isTimeSeries)[source]

Set whether the X-axis is a time series

Parameters:flag (bool) – True to switch to time series, False for regular axis.
setXAxisLogarithmic(flag)[source]

Set the X axis scale between linear and log.

Parameters:flag (bool) – If True, the bottom axis will use a log scale
setYAxisLogarithmic(flag)[source]

Set the Y axis scale between linear and log.

Parameters:flag (bool) – If True, the left axis will use a log scale
setYAxisInverted(flag)[source]

Invert the Y axis.

Parameters:flag (bool) – If True, put the vertical axis origin on the top
isYAxisInverted()[source]

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

isKeepDataAspectRatio()[source]

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

setKeepDataAspectRatio(flag)[source]

Set whether to keep data aspect ratio or not.

Parameters:flag (Boolean, default True) – True to respect data aspect ratio
setGraphGrid(which)[source]

Set grid.

Parameters:which – None to disable grid, ‘major’ for major grid, ‘both’ for major and minor grid
dataToPixel(x, y, axis)[source]

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

Parameters:
  • x (float) – The X coordinate in data space.
  • y (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, check)[source]

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’).
  • check (bool) – True to check if the coordinates are in the plot area.
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()[source]

Plot area bounds in widget coordinates in pixels.

Returns:bounds as a 4-tuple of int: (left, top, width, height)
setAxesDisplayed(displayed)[source]

Display or not the axes.

Parameters:displayed (bool) – If True axes are displayed. If False axes are not anymore visible and the margin used for them is removed.
isAxesDisplayed()[source]

private because in some case it is possible that one of the two axes are displayed and not the other. This only check status set to axes from the public API

backends.BackendMatplotlib

Matplotlib Plot backend.

class silx.gui.plot.backends.BackendMatplotlib.NiceDateLocator(numTicks=5, tz=None)[source]

Matplotlib Locator that uses Nice Numbers algorithm (adapted to dates) to find the tick locations. This results in the same number behaviour as when using the silx Open GL backend.

Expects the data to be posix timestampes (i.e. seconds since 1970)

spacing

The current spacing. Will be updated when new tick value are made

unit

The current DtUnit. Will be updated when new tick value are made

tick_values(vmin, vmax)[source]

Calculates tick values

class silx.gui.plot.backends.BackendMatplotlib.NiceAutoDateFormatter(locator, tz=None)[source]

Matplotlib FuncFormatter that is linked to a NiceDateLocator and gives the best possible formats given the locators current spacing an date unit.

class silx.gui.plot.backends.BackendMatplotlib.BackendMatplotlib(plot, parent=None)[source]

Base class for Matplotlib backend without a FigureCanvas.

For interactive on screen plot, see BackendMatplotlibQt.

See BackendBase.BackendBase for public API documentation.

replot()[source]

Do not perform rendering.

Override in subclass to actually draw something.

setAxesDisplayed(displayed)[source]

Display or not the axes.

Parameters:displayed (bool) – If True axes are displayed. If False axes are not anymore visible and the margin used for them is removed.
class silx.gui.plot.backends.BackendMatplotlib.BackendMatplotlibQt(plot, parent=None)[source]

QWidget matplotlib backend using a QtAgg canvas.

It adds fast overlay drawing and mouse event management.

contextMenuEvent(event)[source]

Override QWidget.contextMenuEvent to implement the context menu

leaveEvent(event)[source]

QWidget event handler

draw()[source]

Overload draw

It performs a full redraw (including overlays) of the plot. It also resets background and emit limits changed signal.

This is directly called by matplotlib for widget resize.

CurvesROIWidget

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

This widget is meant to work with PlotWindow.

ROI are defined by :

  • A name (ROI column)

  • 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 (from column)

  • The x coordinate of the right limit (to column)

  • Raw counts: Sum of the curve’s values in the defined Region Of Intereset.

    ../../../_images/rawCounts.png
  • Net counts: Raw counts minus background

    ../../../_images/netCounts.png
class silx.gui.plot.CurvesROIWidget.CurvesROIWidget(parent=None, name=None, plot=None)[source]

Widget displaying a table of ROI information.

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()[source]

Returns the associated PlotWidget or None

Return type:Union[~silx.gui.plot.PlotWidget,None]
roiFileDir

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

setRois(roidict, order=None)[source]

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 roidict if provided as an OrderedDict.
getRois(order=None)[source]

Return the currently defined ROIs, as an ordered dict.

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: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
setMiddleROIMarkerFlag(flag=True)[source]

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
load(filename)[source]

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

Parameters:filename (str) – The file from which to load ROI
save(filename)[source]

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')[source]

Set the header text of this widget

calculateRois(roiList=None, roiDict=None)[source]

Compute ROI information

class silx.gui.plot.CurvesROIWidget.ROITable(*args, **kwargs)[source]

Table widget displaying ROI information.

See QTableWidget for constructor arguments.

sigROITableSignal

Signal of ROI table modifications.

fillFromROIDict(roilist=(), roidict=None, currentroi=None)[source]

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)
getROIListAndDict()[source]

Return the currently defined ROIs, as a 2-tuple (roiList, roiDict)

roiList is a list of ROI names. roiDict is a dictionary of ROI info.

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 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”)
Returns:ordered dict as a tuple of (list of ROI names, dict of info)
class silx.gui.plot.CurvesROIWidget.CurvesROIDockWidget(parent=None, plot=None, name=None)[source]

QDockWidget with a CurvesROIWidget connected to a PlotWindow.

It makes the link between the CurvesROIWidget and the PlotWindow.

Parameters:
  • parent – See QDockWidget
  • plotPlotWindow 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 = None

Main widget of type CurvesROIWidget

toggleViewAction()[source]

Returns a checkable action that shows or closes this widget.

See QMainWindow.

showEvent(event)[source]

Make sure this widget is raised when it is shown (when it is first created as a tab in PlotWindow or when it is shown again after hiding).

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 silx.gui.plot.Interaction.State(machine)[source]

Base class for the states of a state machine.

This class is meant to be subclassed.

machine

The state machine this state belongs to.

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

goto(state, *args, **kwargs)[source]

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)[source]

Called when the state machine enters this state.

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

leaveState()[source]

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

class silx.gui.plot.Interaction.StateMachine(states, initState, *args, **kwargs)[source]

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)[source]

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
silx.gui.plot.Interaction.LEFT_BTN = 'left'

Left mouse button.

silx.gui.plot.Interaction.RIGHT_BTN = 'right'

Right mouse button.

silx.gui.plot.Interaction.MIDDLE_BTN = 'middle'

Middle mouse button.

class silx.gui.plot.Interaction.ClickOrDrag[source]

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().

click(x, y, btn)[source]

Called upon a left or right button click.

To override in a subclass.

beginDrag(x, y)[source]

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

To override in a subclass.

drag(x, y)[source]

Called on mouse moved during a drag gesture.

To override in a subclass.

endDrag(startPoint, endPoint)[source]

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

To override in a subclass.

LegendSelector

Widget displaying curves legends and allowing to operate on curves.

This widget is meant to work with PlotWindow.

silx.gui.plot.LegendSelector.NoSymbols = (None, 'None', 'none', '', ' ')

List of values resulting in no symbol being displayed for a curve

silx.gui.plot.LegendSelector.LineStyles = {'': 0, ' ': 0, 'None': 0, '-.': 4, 'none': 0, '--': 2, ':': 3, '-': 1, None: 0}

Conversion from matplotlib-like linestyle to Qt

silx.gui.plot.LegendSelector.NoLineStyle = (None, 'None', 'none', '', ' ')

List of style values resulting in no line being displayed for a curve

class silx.gui.plot.LegendSelector.LegendIcon(parent=None)[source]

Object displaying a curve linestyle and symbol.

setSymbolColor(color)[source]
Parameters:color – determines the symbol color
setLineStyle(style)[source]

Set the linestyle.

Possible line styles:

  • ‘’, ‘ ‘, ‘None’: No line
  • ‘-‘: solid
  • ‘–’: dashed
  • ‘:’: dotted
  • ‘-.’: dash and dot
Parameters:style (str) – The linestyle to use
paintEvent(event)[source]
Parameters:event (QPaintEvent) – event
class silx.gui.plot.LegendSelector.LegendModel(legendList=None, parent=None)[source]

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
insertLegendList(row, llist)[source]
Parameters:
  • row (int) – Determines after which row the items are inserted
  • llist (List) – Carries the new legend information
setEditor(event, editor)[source]
Parameters:
  • event (str) – String that identifies the editor
  • editor (QWidget) – Widget used to change data in the underlying model
class silx.gui.plot.LegendSelector.LegendListItemWidget(parent=None, itemType=0)[source]

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

paint(painter, option, modelIndex)[source]

Here be docs..

Parameters:
  • painter (QPainter) –
  • option (QStyleOptionViewItem) –
  • modelIndex (QModelIndex) –
class silx.gui.plot.LegendSelector.LegendListView(parent=None, model=None, contextMenu=None)[source]

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

sigLegendSignal

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

class silx.gui.plot.LegendSelector.LegendListContextMenu(model)[source]

Contextual menu associated to items in a LegendListView.

sigContextMenu

Signal emitting a dict upon contextual menu actions.

class silx.gui.plot.LegendSelector.RenameCurveDialog(parent=None, current='', curves=())[source]

Dialog box to input the name of a curve.

class silx.gui.plot.LegendSelector.LegendsDockWidget(parent=None, plot=None)[source]

QDockWidget with a LegendSelector connected to a PlotWindow.

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

Parameters:
  • parent – See QDockWidget
  • plotPlotWindow instance on which to operate
plot

The PlotWindow this widget is attached to.

renameCurve(oldLegend, newLegend)[source]

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)[source]

Sync the LegendSelector widget displayed info with the plot.

showEvent(event)[source]

Make sure this widget is raised when it is shown (when it is first created as a tab in PlotWindow or when it is shown again after hiding).

_BaseMaskToolsWidget

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

class silx.gui.plot._BaseMaskToolsWidget.BaseMask(dataItem=None)[source]

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

sigUndoable

Signal emitted when undo becomes possible/impossible

sigRedoable

Signal emitted when redo becomes possible/impossible

historyDepth = None

Maximum number of operation stored in history list for undo

setDataItem(item)[source]

Set a data item

Parameters:item – A plot item, subclass of silx.gui.plot.items.Item
Returns:
getDataValues()[source]

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)[source]

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)[source]

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()[source]

Reset history

commit()[source]

Append the current mask to history if changed

undo()[source]

Restore previous mask if any

redo()[source]

Restore previously undone modification if any

clear(level)[source]

Set all values of the given mask level to 0.

Parameters:level (int) – Value of the mask to set to 0.
invert(level)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

Mask/Unmask data located inside a disk 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.
updateLine(level, row0, col0, row1, col1, width, mask=True)[source]

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 silx.gui.plot._BaseMaskToolsWidget.BaseMaskToolsWidget(parent=None, plot=None, mask=None)[source]

Base class for MaskToolsWidget (image mask) and scatterMaskToolsWidget

getSelectionMask(copy=True)[source]

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)[source]

Set the mask: Must be implemented in subclass

resetSelectionMask()[source]

Reset the mask: Must be implemented in subclass

multipleMasks()[source]

Return the current mode of multiple masks support.

See setMultipleMasks()

setMultipleMasks(mode)[source]

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
maskFileDir

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

plot

The PlotWindow this widget is attached to.

setDirection(direction=0)[source]

Set the direction of the layout of the widget

Parameters:direction – QBoxLayout direction
changeEvent(event)[source]

Reset drawing action when disabling widget

save(filename, kind)[source]

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()[source]

Returns the color of the current selected level.

Return type:A tuple or a python array
resetMaskColors(level=None)[source]

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)[source]

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()[source]

masks colors getter

class silx.gui.plot._BaseMaskToolsWidget.BaseMaskToolsDockWidget(parent=None, name='Mask', widget=None)[source]

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)[source]

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)[source]

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()[source]

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

toggleViewAction()[source]

Returns a checkable action that shows or closes this widget.

See QMainWindow.

showEvent(event)[source]

Make sure this widget is raised when it is shown (when it is first created as a tab in PlotWindow or when it is shown again after hiding).

MaskToolsWidget

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

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

class silx.gui.plot.MaskToolsWidget.ImageMask(image=None)[source]

Bases: silx.gui.plot._BaseMaskToolsWidget.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()[source]

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)[source]

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’, or ‘msk’ (if FabIO is installed)
Raises:

Exception – Raised if the file writing fail

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

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)[source]

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)[source]

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)[source]

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.
updateLine(level, row0, col0, row1, col1, width, mask=True)[source]

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 silx.gui.plot.MaskToolsWidget.MaskToolsWidget(parent=None, plot=None)[source]

Bases: silx.gui.plot._BaseMaskToolsWidget.BaseMaskToolsWidget

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

setSelectionMask(mask, copy=True)[source]

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.

load(filename)[source]

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()[source]

Reset the mask

class silx.gui.plot.MaskToolsWidget.MaskToolsDockWidget(parent=None, plot=None, name='Mask')[source]

Bases: silx.gui.plot._BaseMaskToolsWidget.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

class silx.gui.plot.ScatterMaskToolsWidget.ScatterMask(scatter=None)[source]

Bases: silx.gui.plot._BaseMaskToolsWidget.BaseMask

A 1D mask for scatter data.

getDataValues()[source]

Return scatter data values as a 1D array.

Return type:1D numpy.ndarray
updatePoints(level, indices, mask=True)[source]

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)[source]

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)[source]

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)[source]

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.
updateLine(level, y0, x0, y1, x1, width, mask=True)[source]

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 silx.gui.plot.ScatterMaskToolsWidget.ScatterMaskToolsWidget(parent=None, plot=None)[source]

Bases: silx.gui.plot._BaseMaskToolsWidget.BaseMaskToolsWidget

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

setSelectionMask(mask, copy=True)[source]

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.

load(filename)[source]

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()[source]

Reset the mask

class silx.gui.plot.ScatterMaskToolsWidget.ScatterMaskToolsDockWidget(parent=None, plot=None, name='Mask')[source]

Bases: silx.gui.plot._BaseMaskToolsWidget.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.

silx.gui.plot.PlotEvents.prepareDrawingSignal(event, type_, points, parameters=None)[source]

See Plot documentation for content of events

silx.gui.plot.PlotEvents.prepareMouseSignal(eventType, button, xData, yData, xPixel, yPixel)[source]

See Plot documentation for content of events

silx.gui.plot.PlotEvents.prepareHoverSignal(label, type_, posData, posPixel, draggable, selectable)[source]

See Plot documentation for content of events

silx.gui.plot.PlotEvents.prepareMarkerSignal(eventType, button, label, type_, draggable, selectable, posDataMarker, posPixelCursor=None, posDataCursor=None)[source]

See Plot documentation for content of events

silx.gui.plot.PlotEvents.prepareImageSignal(button, label, type_, col, row, x, y, xPixel, yPixel)[source]

See Plot documentation for content of events

silx.gui.plot.PlotEvents.prepareCurveSignal(button, label, type_, xData, yData, x, y, xPixel, yPixel)[source]

See Plot documentation for content of events

silx.gui.plot.PlotEvents.prepareLimitsChangedSignal(sourceObj, xRange, yRange, y2Range)[source]

See Plot documentation for content of events

PlotInteraction

Implementation of the interaction for the Plot.

class silx.gui.plot.PlotInteraction.Pan(plot)[source]

Pan plot content and zoom on wheel state machine.

class silx.gui.plot.PlotInteraction.Zoom(plot, color)[source]

Zoom-in/out state machine.

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

class silx.gui.plot.PlotInteraction.Select(plot, parameters, states, state)[source]

Base class for drawing selection areas.

class silx.gui.plot.PlotInteraction.SelectPolygon(plot, parameters)[source]

Drawing selection polygon area state machine.

getDragThreshold()[source]

Return dragging ratio with device to pixel ratio applied.

Return type:float
class silx.gui.plot.PlotInteraction.Select2Points(plot, parameters)[source]

Base class for drawing selection based on 2 input points.

class silx.gui.plot.PlotInteraction.SelectRectangle(plot, parameters)[source]

Drawing rectangle selection area state machine.

class silx.gui.plot.PlotInteraction.SelectLine(plot, parameters)[source]

Drawing line selection area state machine.

class silx.gui.plot.PlotInteraction.Select1Point(plot, parameters)[source]

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

class silx.gui.plot.PlotInteraction.SelectHLine(plot, parameters)[source]

Drawing a horizontal line selection area state machine.

class silx.gui.plot.PlotInteraction.SelectVLine(plot, parameters)[source]

Drawing a vertical line selection area state machine.

class silx.gui.plot.PlotInteraction.DrawFreeHand(plot, parameters)[source]

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

class silx.gui.plot.PlotInteraction.SelectFreeLine(plot, parameters)[source]

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

class silx.gui.plot.PlotInteraction.ItemsInteraction(plot)[source]

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.

click(x, y, btn)[source]

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)[source]

Handle begining of drag interaction

Parameters:
  • x – X position of the mouse in pixels
  • y – Y position of the mouse in pixels
Returns:

True if drag is catched by an item, False otherwise

class silx.gui.plot.PlotInteraction.ItemsInteractionForCombo(plot)[source]

Interaction with items to combine through FocusManager.

class silx.gui.plot.PlotInteraction.FocusManager(eventHandlers=())[source]

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 silx.gui.plot.PlotInteraction.ZoomAndSelect(plot, color)[source]

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
color

Color of the zoom area

click(x, y, btn)[source]

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)[source]

Handle start drag and switching between zoom and item drag.

Parameters:
  • x – X position in pixels
  • y – Y position in pixels
drag(x, y)[source]

Handle drag, eventually forwarding to zoom.

Parameters:
  • x – X position in pixels
  • y – Y position in pixels
endDrag(startPos, endPos)[source]

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
class silx.gui.plot.PlotInteraction.PanAndSelect(plot)[source]

Combine Pan and ItemInteraction state machine.

Parameters:plot – The Plot to which this interaction is attached
click(x, y, btn)[source]

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)[source]

Handle start drag and switching between zoom and item drag.

Parameters:
  • x – X position in pixels
  • y – Y position in pixels
drag(x, y)[source]

Handle drag, eventually forwarding to zoom.

Parameters:
  • x – X position in pixels
  • y – Y position in pixels
endDrag(startPos, endPos)[source]

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
class silx.gui.plot.PlotInteraction.PlotInteraction(plot)[source]

Proxy to currently use state machine for interaction.

This allows to switch interactive mode.

Parameters:plot – The Plot to apply interaction to
zoomOnWheel = None

True to enable zoom on wheel, False otherwise.

getInteractiveMode()[source]

Returns the current interactive mode as a dict.

The returned dict contains at least the key ‘mode’. Mode can be: ‘draw’, ‘pan’, ‘select’, ‘zoom’. It can also contains extra keys (e.g., ‘color’) specific to a mode as provided to setInteractiveMode().

setInteractiveMode(mode, color='black', shape='polygon', label=None, width=None)[source]

Switch the interactive mode.

Parameters:
  • mode (str) – The name of the interactive mode. In ‘draw’, ‘pan’, ‘select’, ‘select-draw’, ‘zoom’.
  • color (Color description: The name as a str or a tuple of 4 floats or None.) – Only for ‘draw’ and ‘zoom’ modes. Color to use for drawing selection area. Default black. If None, selection area is not drawn.
  • shape (str) – Only for ‘draw’ mode. The kind of shape to draw. In ‘polygon’, ‘rectangle’, ‘line’, ‘vline’, ‘hline’, ‘polylines’. Default is ‘polygon’.
  • label (str) – Only for ‘draw’ mode.
  • width (float) – Width of the pencil. Only for draw pencil mode.
handleEvent(event, *args, **kwargs)[source]

Forward event to current interactive mode state machine.

_utils

Miscellaneous utility functions for the Plot

silx.gui.plot._utils.addMarginsToLimits(margins, isXLog, isYLog, xMin, xMax, yMin, yMax, y2Min=None, y2Max=None)[source]

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.

silx.gui.plot._utils.ticklayout.numberOfDigits(tickSpacing)[source]

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
silx.gui.plot._utils.ticklayout.niceNumGeneric(value, niceFractions=None, isRound=False)[source]

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].

silx.gui.plot._utils.ticklayout.niceNumbers(vMin, vMax, nTicks=5)[source]

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

silx.gui.plot._utils.ticklayout.ticks(vMin, vMax, nbTicks=5)[source]

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

silx.gui.plot._utils.ticklayout.niceNumbersAdaptative(vMin, vMax, axisLength, tickDensity)[source]

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

silx.gui.plot._utils.ticklayout.niceNumbersForLog10(minLog, maxLog, nTicks=5)[source]

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

silx.gui.plot._utils.ticklayout.niceNumbersAdaptativeForLog10(vMin, vMax, axisLength, tickDensity)[source]

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

silx.gui.plot._utils.ticklayout.computeLogSubTicks(ticks, lowBound, highBound)[source]

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)