PlotWidget: Base class for plotting widgets

The PlotWidget is a Qt widget providing the plot API initially provided in PyMca. It is the basis of other plot widget, thus all plot widgets share the same API.

For an introduction and examples of the plot API, see Getting started with plot widgets.

Plot API

This is a choosen subset of the complete plot API, the full API is documented in silx.gui.plot.Plot.

class silx.gui.plot.PlotWidget.PlotWidget(parent=None, backend=None, legends=False, callback=None, **kw)[source]

Bases: PyQt4.QtGui.QMainWindow, silx.gui.plot.Plot.Plot

Qt Widget providing a 1D/2D plot.

This widget is a QMainWindow. It provides Qt signals for the Plot and add supports for panning with arrow keys.

Parameters:
  • parent – The parent of this widget or None.
  • backend (str or BackendBase.BackendBase) – The backend to use for the plot. The default is to use matplotlib.

Plot data

Those methods allow to add and update plotted data:

PlotWidget.addCurve(x, y, legend=None, info=None, replace=False, replot=None, color=None, symbol=None, linewidth=None, linestyle=None, xlabel=None, ylabel=None, yaxis=None, xerror=None, yerror=None, z=None, selectable=None, fill=None, resetzoom=True, histogram=None, **kw)

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

Curves are uniquely identified by their legend. To add multiple curves, call addCurve() multiple times with different legend argument. To replace/update an existing curve, call addCurve() with the existing curve legend. If you wan’t to display the curve values as an histogram see the histogram parameter.

When curve parameters are not provided, if a curve with the same legend is displayed in the plot, its parameters are used.

Parameters:
  • x (numpy.ndarray) – The data corresponding to the x coordinates. If you attempt to plot an histogram you can set edges values in x. In this case len(x) = len(y) + 1
  • y (numpy.ndarray) – The data corresponding to the y coordinates
  • legend (str) – The legend to be associated to the curve (or None)
  • info – User-defined information associated to the curve
  • replace (bool) – True (the default) to delete already existing curves
  • color (str (“#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:

    - 'o' circle
    - '.' point
    - ',' pixel
    - '+' cross
    - 'x' x-cross
    - 'd' diamond
    - 's' square
    - None (the default) to use default symbol
    
  • linewidth (float) – The width of the curve in pixels (Default: 1).
  • linestyle (str) –

    Type of line:

    - ' '  no line
    - '-'  solid line
    - '--' dashed line
    - '-.' dash-dot line
    - ':'  dotted line
    - None (the default) to use default line style
    
  • xlabel (str) – Label to show on the X axis when the curve is active or None to keep default axis label.
  • ylabel (str) – Label to show on the Y axis when the curve is active or None to keep default axis label.
  • yaxis (str) – The Y axis this curve is attached to. Either ‘left’ (the default) or ‘right’
  • xerror (A float, or a numpy.ndarray of float32. If it is an array, it can either be a 1D array of same length as the data or a 2D array with 2 rows of same length as the data: row 0 for positive errors, row 1 for negative errors.) – Values with the uncertainties on the x values
  • yerror (A float, or a numpy.ndarray of float32. See xerror.) – Values with the uncertainties on the y values
  • z (int) – Layer on which to draw the curve (default: 1) This allows to control the overlay.
  • selectable (bool) – Indicate if the curve can be selected. (Default: True)
  • fill (bool) – True to fill the curve, False otherwise (default).
  • resetzoom (bool) – True (the default) to reset the zoom.
  • histogram (str) –

    if not None then the curve will be draw as an histogram. The step for each values of the curve can be set to the left, center or right of the original x curve values. If histogram is not None and len(x) == len(y+1) then x is directly take as edges of the histogram. Type of histogram:

    - None (default)
    - 'left'
    - 'right'
    - 'center'
    
Returns:

The key string identify this curve

PlotWidget.addImage(data, legend=None, info=None, replace=True, replot=None, xScale=None, yScale=None, z=None, selectable=False, draggable=False, colormap=None, pixmap=None, xlabel=None, ylabel=None, origin=None, scale=None, resetzoom=True, **kw)

Add a 2D dataset or an image to the plot.

It displays either an array of data using a colormap or a RGB(A) image.

Images are uniquely identified by their legend. To add multiple images, call addImage() multiple times with different legend argument. To replace/update an existing image, call addImage() with the existing image legend.

When image parameters are not provided, if an image with the same legend is displayed in the plot, its parameters are used.

Parameters:
  • data (numpy.ndarray) – (nrows, ncolumns) data or (nrows, ncolumns, RGBA) ubyte array
  • legend (str) – The legend to be associated to the image (or None)
  • info – User-defined information associated to the image
  • replace (bool) – True (default) to delete already existing images
  • z (int) – Layer on which to draw the image (default: 0) This allows to control the overlay.
  • selectable (bool) – Indicate if the image can be selected. (default: False)
  • draggable (bool) – Indicate if the image can be moved. (default: False)
  • colormap (dict) – Description of the colormap to use (or None) This is ignored if data is a RGB(A) image. See Plot for the documentation of the colormap dict.
  • pixmap ((nrows, ncolumns, RGBA) ubyte array or None (default)) – Pixmap representation of the data (if any)
  • xlabel (str) – X axis label to show when this curve is active, or None to keep default axis label.
  • ylabel (str) – Y axis label to show when this curve is active, or None to keep default axis label.
  • origin (float or 2-tuple of float) – (origin X, origin Y) of the data. It is possible to pass a single float if both coordinates are equal. Default: (0., 0.)
  • scale (float or 2-tuple of float) – (scale X, scale Y) of the data. It is possible to pass a single float if both coordinates are equal. Default: (1., 1.)
  • resetzoom (bool) – True (the default) to reset the zoom.
Returns:

The key string identify this image

Plot markers

It is also possible to add point or line markers to the plot:

PlotWidget.addMarker(x, y, legend=None, text=None, color=None, selectable=False, draggable=False, symbol='+', constraint=None, **kw)

Add a point marker to the plot.

Markers are uniquely identified by their legend. As opposed to curves, images and items, two calls to addMarker() without legend argument adds two markers with different identifying legends.

Parameters:
  • x (float) – Position of the marker on the X axis in data coordinates
  • y (float) – Position of the marker on the Y axis in data coordinates
  • legend (str) – Legend associated to the marker to identify it
  • text (str) – Text to display next to the marker
  • color (str) – Color of the marker, e.g., ‘blue’, ‘b’, ‘#FF0000’ (Default: ‘black’)
  • selectable (bool) – Indicate if the marker can be selected. (default: False)
  • draggable (bool) – Indicate if the marker can be moved. (default: False)
  • symbol (str) –

    Symbol representing the marker in:

    - 'o' circle
    - '.' point
    - ',' pixel
    - '+' cross (the default)
    - '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:

The key string identify this marker

PlotWidget.addXMarker(x, legend=None, text=None, color=None, selectable=False, draggable=False, constraint=None, **kw)

Add a vertical line marker to the plot.

Markers are uniquely identified by their legend. As opposed to curves, images and items, two calls to addXMarker() without legend argument adds two markers with different identifying legends.

Parameters:
  • x (float) – Position of the marker on the X axis in data coordinates
  • legend (str) – Legend associated to the marker to identify it
  • text (str) – Text to display on the marker.
  • color (str) – Color of the marker, e.g., ‘blue’, ‘b’, ‘#FF0000’ (Default: ‘black’)
  • selectable (bool) – Indicate if the marker can be selected. (default: False)
  • draggable (bool) – Indicate if the marker can be moved. (default: False)
  • 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:

The key string identify this marker

PlotWidget.addYMarker(y, legend=None, text=None, color=None, selectable=False, draggable=False, constraint=None, **kw)

Add a horizontal line marker to the plot.

Markers are uniquely identified by their legend. As opposed to curves, images and items, two calls to addYMarker() without legend argument adds two markers with different identifying legends.

Parameters:
  • y (float) – Position of the marker on the Y axis in data coordinates
  • legend (str) – Legend associated to the marker to identify it
  • text (str) – Text to display next to the marker.
  • color (str) – Color of the marker, e.g., ‘blue’, ‘b’, ‘#FF0000’ (Default: ‘black’)
  • selectable (bool) – Indicate if the marker can be selected. (default: False)
  • draggable (bool) – Indicate if the marker can be moved. (default: False)
  • 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:

The key string identify this marker

Remove data from the plot

PlotWidget.clear()

Remove everything from the plot.

PlotWidget.remove(legend=None, kind=('curve', 'image', 'item', 'marker'))

Remove one or all element(s) of the given legend and kind.

Examples:

  • remove() clears the plot
  • remove(kind='curve') removes all curves from the plot
  • remove('myCurve', kind='curve') removes the curve with legend ‘myCurve’ from the plot.
  • remove('myImage, kind='image') removes the image with legend ‘myImage’ from the plot.
  • remove('myImage') removes elements (for instance curve, image, item and marker) with legend ‘myImage’.
Parameters:
  • legend (str) – The legend associated to the element to remove, or None to remove
  • kind (str or tuple of str to specify multiple kinds.) – The kind of elements to remove from the plot. In: ‘all’, ‘curve’, ‘image’, ‘item’, ‘marker’. By default, it removes all kind of elements.

Title and labels

Those methods handle the text labels of the axes and the plot title:

PlotWidget.getGraphTitle()

Return the plot main title as a str.

PlotWidget.setGraphTitle(title='')

Set the plot main title.

Parameters:title (str) – Main title of the plot (default: ‘’)
PlotWidget.getGraphXLabel()

Return the current X axis label as a str.

PlotWidget.setGraphXLabel(label='X')

Set the plot X axis label.

The provided label can be temporarily replaced by the X label of the active curve if any.

Parameters:label (str) – The X axis label (default: ‘X’)
PlotWidget.getGraphYLabel(axis='left')

Return the current Y axis label as a str.

Parameters:axis (str) – The Y axis for which to get the label (left or right)
PlotWidget.setGraphYLabel(label='Y', axis='left')

Set the plot Y axis label.

The provided label can be temporarily replaced by the Y label of the active curve if any.

Parameters:
  • label (str) – The Y axis label (default: ‘Y’)
  • axis (str) – The Y axis for which to set the label (left or right)

Axes limits

Those methods change the range of data values displayed on each axis.

PlotWidget.getGraphXLimits()

Get the graph X (bottom) limits.

Returns:Minimum and maximum values of the X axis
PlotWidget.setGraphXLimits(xmin, xmax, replot=None)

Set the graph X (bottom) limits.

Parameters:
  • xmin (float) – minimum bottom axis value
  • xmax (float) – maximum bottom axis value
PlotWidget.getGraphYLimits(axis='left')

Get the graph Y limits.

Parameters:axis (str) – The axis for which to get the limits: Either ‘left’ or ‘right’
Returns:Minimum and maximum values of the X axis
PlotWidget.setGraphYLimits(ymin, ymax, axis='left', replot=None)

Set the graph Y limits.

Parameters:
  • xmin (float) – minimum bottom axis value
  • xmax (float) – maximum bottom axis value
  • axis (str) – The axis for which to get the limits: Either ‘left’ or ‘right’
PlotWidget.setLimits(xmin, xmax, ymin, ymax, y2min=None, y2max=None)

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

If y2min or y2max is None, the right Y axis limits are not updated.

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 or None (the default)
  • y2max (float) – maximum right axis value or None (the default)

Axes

The following methods handle the display properties of the axes:

PlotWidget.isXAxisLogarithmic()

Return True if X axis scale is logarithmic, False if linear.

PlotWidget.setXAxisLogarithmic(flag)

Set the bottom X axis scale (either linear or logarithmic).

Parameters:flag (bool) – True to use a logarithmic scale, False for linear.
PlotWidget.isYAxisLogarithmic()

Return True if Y axis scale is logarithmic, False if linear.

PlotWidget.setYAxisLogarithmic(flag)

Set the Y axes scale (either linear or logarithmic).

Parameters:flag (bool) – True to use a logarithmic scale, False for linear.
PlotWidget.isYAxisInverted()

Return True if Y axis goes from top to bottom, False otherwise.

PlotWidget.setYAxisInverted(flag=True)

Set the Y axis orientation.

Parameters:flag (bool) – True for Y axis going from top to bottom, False for Y axis going from bottom to top
PlotWidget.isKeepDataAspectRatio()

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

PlotWidget.setKeepDataAspectRatio(flag=True)

Set whether the plot keeps data aspect ratio or not.

Parameters:flag (bool) – True to respect data aspect ratio
PlotWidget.getGraphGrid()

Return the current grid mode, either None, ‘major’ or ‘both’.

See setGraphGrid().

PlotWidget.setGraphGrid(which=True)

Set the type of grid to display.

Parameters:which (str of bool) – None or False to disable the grid, ‘major’ or True for grid on major ticks (the default), ‘both’ for grid on both major and minor ticks.

Reset zoom

PlotWidget.resetZoom(dataMargins=None)

Reset the plot limits to the bounds of the data and redraw the plot.

It automatically scale limits of axes that are in autoscale mode (See setXAxisAutoScale(), setYAxisAutoScale()). It keeps current limits on axes that are not in autoscale mode.

Extra margins can be added around the data inside the plot area. Margins are given as one ratio of the data range per limit of the data (xMin, xMax, yMin and yMax limits). For log scale, extra margins are applied in log10 of the data.

Parameters:dataMargins (A 4-tuple of float as (xMin, xMax, yMin, yMax).) – Ratios of margins to add around the data inside the plot area for each side (Default: no margins).

Those methods change the behavior of PlotWidget.resetZoom().

PlotWidget.getDataMargins()

Get the default data margin ratios, see setDataMargins().

Returns:The margin ratios for each side (xMin, xMax, yMin, yMax).
Return type:A 4-tuple of floats.
PlotWidget.setDataMargins(xMinMargin=0.0, xMaxMargin=0.0, yMinMargin=0.0, yMaxMargin=0.0)

Set the default data margins to use in resetZoom().

Set the default ratios of margins (as floats) to add around the data inside the plot area for each side.

PlotWidget.isXAxisAutoScale()

Return True if X axis is automatically adjusting its limits.

PlotWidget.setXAxisAutoScale(flag=True)

Set the X axis limits adjusting behavior of resetZoom().

Parameters:flag (bool) – True to resize limits automatically, False to disable it.
PlotWidget.isYAxisAutoScale()

Return True if Y axes are automatically adjusting its limits.

PlotWidget.setYAxisAutoScale(flag=True)

Set the Y axis limits adjusting behavior of resetZoom().

Parameters:flag (bool) – True to resize limits automatically, False to disable it.

Defaults

Those methods set-up default values for PlotWidget.addCurve() and PlotWidget.addImage():

PlotWidget.getDefaultColormap()

Return the default colormap used by addImage() as a dict.

See Plot for the documentation of the colormap dict.

PlotWidget.setDefaultColormap(colormap=None)

Set the default colormap used by addImage().

Setting the default colormap do not change any currently displayed image. It only affects future calls to addImage() without the colormap parameter.

Parameters:colormap (dict) – The description of the default colormap, or None to set the colormap to a linear autoscale gray colormap. See Plot for the documentation of the colormap dict.
PlotWidget.getSupportedColormaps()

Get the supported colormap names as a tuple of str.

The list should at least contain and start by: (‘gray’, ‘reversed gray’, ‘temperature’, ‘red’, ‘green’, ‘blue’)

PlotWidget.setDefaultPlotPoints(flag)

Set the default symbol of all curves.

When called, this reset the symbol of all existing curves.

Parameters:flag (bool) – True to use ‘o’ as the default curve symbol, False to use no symbol.
PlotWidget.setDefaultPlotLines(flag)

Toggle the use of lines as the default curve line style.

Parameters:flag (bool) – True to use a line as the default line style, False to use no line as the default line style.

Interaction

Those methods allow to change the interaction mode (e.g., drawing mode) of the plot and to toggle the use of a crosshair cursor:

PlotWidget.getInteractiveMode()

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

PlotWidget.setInteractiveMode(mode, color='black', shape='polygon', label=None, zoomOnWheel=True, source=None, width=None)

Switch the interactive mode.

Parameters:
  • mode (str) – The name of the interactive mode. In ‘draw’, ‘pan’, ‘select’, ‘zoom’.
  • color (Color description: The name as a str or a tuple of 4 floats.) – Only for ‘draw’ and ‘zoom’ modes. Color to use for drawing selection area. Default black.
  • shape (str) – Only for ‘draw’ mode. The kind of shape to draw. In ‘polygon’, ‘rectangle’, ‘line’, ‘vline’, ‘hline’, ‘freeline’. Default is ‘polygon’.
  • label (str) – Only for ‘draw’ mode, sent in drawing events.
  • zoomOnWheel (bool) – Toggle zoom on wheel support
  • source – A user-defined object (typically the caller object) that will be send in the interactiveModeChanged event, to identify which object required a mode change. Default: None
  • width (float) – Width of the pencil. Only for draw pencil mode.
PlotWidget.getGraphCursor()

Returns the state of the crosshair cursor.

See setGraphCursor().

Returns:None if the crosshair cursor is not active, else a tuple (color, linewidth, linestyle).
PlotWidget.setGraphCursor(flag=False, color='black', linewidth=1, linestyle='-')

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

Parameters:
  • flag (bool) – Toggle the display of a crosshair cursor. The crosshair cursor is hidden by default.
  • color (A string (either a predefined color name in Colors.py or “#RRGGBB”)) or a 4 columns unsigned byte array (Default: black).) – The color to use for the crosshair.
  • linewidth (int) – The width of the lines of the crosshair (Default: 1).
  • linestyle (str) –

    Type of line:

    - ' ' no line
    - '-' solid line (the default)
    - '--' dashed line
    - '-.' dash-dot line
    - ':' dotted line
    

Misc.

PlotWidget.saveGraph(filename, fileFormat=None, dpi=None, **kw)

Save a snapshot of the plot.

Supported file formats: “png”, “svg”, “pdf”, “ps”, “eps”, “tif”, “tiff”, “jpeg”, “jpg”.

Parameters:
  • filename (str, StringIO or BytesIO) – Destination
  • fileFormat (str) – String specifying the format
Returns:

False if cannot save the plot, True otherwise

Signals

The PlotWidget provides the following Qt signals:

PlotWidget.sigPlotSignal

Signal for all events of the plot.

The signal information is provided as a dict. See Plot for documentation of the content of the dict.

PlotWidget.sigSetYAxisInverted

Signal emitted when Y axis orientation has changed

PlotWidget.sigSetXAxisLogarithmic

Signal emitted when X axis scale has changed

PlotWidget.sigSetYAxisLogarithmic

Signal emitted when Y axis scale has changed

PlotWidget.sigSetXAxisAutoScale

Signal emitted when X axis autoscale has changed

PlotWidget.sigSetYAxisAutoScale

Signal emitted when Y axis autoscale has changed

PlotWidget.sigSetKeepDataAspectRatio

Signal emitted when plot keep aspect ratio has changed

PlotWidget.sigSetGraphGrid

Signal emitted when plot grid has changed

PlotWidget.sigSetGraphCursor

Signal emitted when plot crosshair cursor has changed

PlotWidget.sigSetPanWithArrowKeys

Signal emitted when pan with arrow keys has changed

PlotWidget.sigContentChanged

Signal emitted when the content of the plot is changed.

It provides 3 informations:

  • action: The change of the plot: ‘add’ or ‘remove’
  • kind: The kind of primitive changed: ‘curve’, ‘image’, ‘item’ or ‘marker’
  • legend: The legend of the primitive changed.
PlotWidget.sigActiveCurveChanged

Signal emitted when the active curve has changed.

It provides 2 informations:

  • previous: The legend of the previous active curve or None
  • legend: The legend of the new active curve or None if no curve is active
PlotWidget.sigActiveImageChanged

Signal emitted when the active image has changed.

It provides 2 informations:

  • previous: The legend of the previous active image or None
  • legend: The legend of the new active image or None if no image is active
PlotWidget.sigInteractiveModeChanged

Signal emitted when the interactive mode has changed

It provides the source as passed to setInteractiveMode().