Getting started with plot widgets#

This introduction to silx.gui.plot covers the following topics:

For a complete description of the API, see silx.gui.plot.

Use silx.gui.plot from (I)Python console#

From a Python or IPython interpreter, the simplest way is to import the silx.sx module:

>>> from silx import sx

The silx.sx module initialises Qt and provides access to silx.gui.plot widgets and extra plot functions.

Note

The silx.sx module does NOT initialise Qt and does NOT expose silx widget in a notebook.

An alternative to run silx.gui widgets from IPython, is to set IPython to use Qt(5), e.g., with the –gui option:

ipython --gui=qt5

Compatibility with IPython#

silx widgets require Qt to be initialized. If Qt is not yet loaded, silx tries to load PyQt5 first before trying other supported bindings.

With versions of IPython lower than 3.0 (e.g., on Debian 8), there is an incompatibility between the way silx loads Qt and the way IPython is doing it through the --gui option, %gui or %pylab magics. In this case, IPython magics that initialize Qt might not work after importing modules from silx.gui.

On Linux and MacOS X, run from the command line:

QT_API=pyqt ipython

On Windows, run from the command line:

set QT_API=pyqt&&ipython

Plot functions#

The silx.sx module provides functions to plot curves and images with silx.gui.plot widgets:

  • plot() for curves, e.g., sx.plot(y) or sx.plot(x, y)

  • imshow() for images, e.g., sx.imshow(image)

See silx.sx for documentation and how to use it.

For more features, use widgets directly (see Plot curves in a widget and Plot images in a widget).

Use silx.gui.plot from a script#

A Qt GUI script must have a QApplication initialised before creating widgets:

from silx.gui import qt

[...]

qapp = qt.QApplication([])

[...] # Widgets initialisation

if __name__ == '__main__':
    [...]
    qapp.exec()

Unless a Qt binding has already been loaded, silx.gui.qt uses one of the supported Qt bindings (PyQt5, PySide6, PyQt6). If you prefer to choose the Qt binding yourself, import it before importing a module from silx.gui:

import PyQt5.QtCore  # Importing PyQt5 will force silx to use it
from silx.gui import qt

Plot curves in a widget#

The Plot1D widget provides a plotting area and a toolbar with tools useful for curves such as setting a logarithmic scale or defining a region of interest.

First, create a Plot1D widget:

from silx.gui.plot import Plot1D

plot = Plot1D()  # Create the plot widget
plot.show()  # Make the plot widget visible

One curve#

To display a single curve, use the PlotWidget.addCurve() method:

plot.addCurve(x=(1, 2, 3), y=(3, 2, 1), legend='curve')  # Add a curve named 'curve'

When you need to update this curve, first get the curve invoking PlotWidget.getCurve() and update its points invoking the curve’s setData() method:

mycurve = plot.getCurve('curve')  # Retrieve the curve
mycurve.setData(x=(1, 2, 3), y=(1, 2, 3))  # Update its data

To clear the plot, call PlotWidget.clear():

plot.clear()

Multiple curves#

In order to display multiple curves in a frame, you need to provide a different legend string for each of them:

import numpy

x = numpy.linspace(-numpy.pi, numpy.pi, 1000)
plot.addCurve(x, numpy.sin(x), legend='sinus')
plot.addCurve(x, numpy.cos(x), legend='cosinus')
plot.addCurve(x, numpy.random.random(len(x)), legend='random')

To update a curve, call PlotWidget.getCurve() with the legend of the curve you want to update, and update its data through setData():

curve = plot.getCurve('random')
curve.setData(x, numpy.random.random(len(x)) - 1.)

To remove a curve from the plot, call PlotWidget.remove() with the legend of the curve you want to remove:

plot.remove('random')

To clear the plotting area, call PlotWidget.clear():

plot.clear()

Curve style#

By default, different curves will automatically be displayed using different styles, and keep the same style when updating the plot.

It is possible to specify the color of the curve, its linewidth and linestyle as well as the symbol to use as marker for data points (See PlotWidget.addCurve() for more details):

import numpy

x = numpy.linspace(-numpy.pi, numpy.pi, 100)

# Curve with a thick dashed line
plot.addCurve(x, numpy.sin(x), legend='sinus',
              linewidth=3, linestyle='--')

# Curve with pink markers only
plot.addCurve(x, numpy.cos(x), legend='cosinus',
              color='pink', linestyle=' ', symbol='o')

# Curve with green line with square markers
plot.addCurve(x, numpy.random.random(len(x)), legend='random',
              color='green', linestyle='-', symbol='s')

Histogram#

To display histograms, use PlotWidget.addHistogram():

import numpy
values = numpy.arange(20)  # Values of the histogram
edges = numpy.arange(21)  # Edges of the bins (number of values + 1)
plot.addHistogram(values, edges, legend='histo1', fill=True, color='green')

Alternatively, PlotWidget.addCurve() can be used to display histograms with the histogram argument. (See PlotWidget.addCurve() for more details).

import numpy
x = numpy.arange(0, 20, 1)
plot.addCurve(x, x+1, legend='histo2', histogram='center', fill=False, color='black')

Histogram bins can be centred on x values or set on the left hand side or the right hand side of the given x values.

Plot images in a widget#

The Plot2D widget provides a plotting area and a toolbar with tools useful for images, such as keeping the aspect ratio, changing the colormap or defining a mask.

First, create a Plot2D widget:

from silx.gui.plot import Plot2D

plot = Plot2D()  # Create the plot widget
plot.show()  # Make the plot widget visible

One image#

To display a single image, use the PlotWidget.addImage() method:

import numpy

data = numpy.random.random(512 * 512).reshape(512, -1)  # Create 2D image
plot.addImage(data, legend='image')  # Plot the 2D data set with default colormap

To update this image, call PlotWidget.getImage() with its legend and update its data with setData():

data2 = numpy.arange(512*512).reshape(512, 512)

image = plot.getImage('image')  # Retrieve the image
image.setData(data2)  # Update the displayed data

PlotWidget.addImage() supports both 2D arrays of data displayed with a colormap and RGB(A) images as 3D arrays of shape (height, width, color channels).

To clear the plot area, call PlotWidget.clear():

plot.clear()

Origin and scale#

When displaying an image, it is possible to define the origin and the scale of the image array in the plot area coordinates:

data = numpy.random.random(512 * 512).reshape(512, -1)
plot.addImage(data, legend='image', origin=(100, 100), scale=(0.1, 0.1))

Colormap#

A colormap is described with a Colormap class as follows:

from silx.gui.colors import Colormap

colormap = Colormap(name='gray',             # Name of the colormap
                    normalization='linear',  # Either 'linear' or 'log'
                    vmin=0.0,                # If not autoscale, data value to bind to min of colormap
                    vmax=1.0                 # If not autoscale, data value to bind to max of colormap
            )

The following colormap names are guaranteed to be available:

  • gray

  • reversed gray

  • temperature

  • red

  • green

  • blue

  • viridis

  • magma

  • inferno

  • plasma

Yet, any colormap name from matplotlib (see Choosing Colormaps) should work.

It is possible to change the default colormap of the plot widget by PlotWidget.setDefaultColormap() (and to get it with PlotWidget.getDefaultColormap()):

from silx.gui.colors import Colormap

colormap = Colormap(name='viridis',
                    normalization='linear',
                    vmin=0.0,
                    vmax=10000.0)
plot.setDefaultColormap(colormap)

data = numpy.arange(512 * 512.).reshape(512, -1)
plot.addImage(data)  # Rendered with the default colormap set before

It is also possible to provide a Colormap to PlotWidget.addImage() to override this default for an image:

colormap = Colormap(name='magma',
                    normalization='log',
                    vmin=1.8,
                    vmax=2.2)
data = numpy.random.random(512 * 512).reshape(512, -1) + 1.
plot.addImage(data, colormap=colormap)

The colormap can be changed by the user from the widget’s toolbar.

Multiple images#

In order to display multiple images in a frame, you need to provide a different legend string for each of them and to set the replace argument to False:

data = numpy.random.random(512 * 512).reshape(512, -1)
plot.addImage(data, legend='random', replace=False)

data = numpy.arange(512 * 512.).reshape(512, -1)
plot.addImage(data, legend='arange', replace=False, origin=(512, 512))

To update an image, call PlotWidget.getImage() with the legend to get the corresponding curve. Update its data values using setData().

data = (512 * 512. - numpy.arange(512 * 512.)).reshape(512, -1)
arange_image = plot.getImage('arange')
arange_image.setData(data)

To remove an image from a plot, call PlotWidget.remove() with the legend of the image you want to remove:

plot.remove('random')

Configure plot axes#

The following examples illustrate the API to configure the plot axes. PlotWidget.getXAxis() and PlotWidget.getYAxis() give access to each plot axis (items.Axis) in order to configure them.

Labels and title#

Use PlotWidget.setGraphTitle() to set the plot main title. Use PlotWidget.getXAxis() and PlotWidget.getYAxis() to get the axes and set their text label with items.Axis.setLabel():

plot.setGraphTitle('My plot')
plot.getXAxis().setLabel('X')
plot.getYAxis().setLabel('Y')

Axes limits#

Different methods allow to retrieve and set the data limits displayed on each axis.

The following code moves the visible plot area to the right:

xmin, xmax = plot.getXAxis().getLimits()
offset = 0.1 * (xmax - xmin)
plot.getXAxis().setLimits(xmin + offset, xmax + offset)

PlotWidget.resetZoom() set the plot limits to the upper and lower bounds of the data:

plot.resetZoom()

See PlotWidget.resetZoom(), PlotWidget.setLimits(), PlotWidget.getXAxis(), PlotWidget.getYAxis() and items.Axis for details.

Axes#

The axes of a plot can be modified via different methods:

plot.getYAxis().setInverted(True)  # Makes the Y axis pointing downward
plot.setKeepDataAspectRatio(True)  # To keep aspect ratio between X and Y axes

See PlotWidget.getYAxis(), PlotWidget.setKeepDataAspectRatio() for details.

plot.setGraphGrid(which='both')  # To show a grid for both minor and major axes ticks

# Use logarithmic axes
plot.getXAxis().setScale("log")
plot.getYAxis().setScale("log")

See PlotWidget.setGraphGrid(), PlotWidget.getXAxis(), PlotWidget.getXAxis() and items.Axis for details.