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

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.

Compatibility with IPython

To run silx.gui widgets from IPython, IPython must be set to use Qt (and in case of using PyQt4 and Python 2.7, PyQt must be set to use API version 2, see note below for explanation).

As silx is configuring the Qt binding and matplotlib, the safest way to use silx from IPython is to import silx.gui.plot first and then run either %gui qt or %pylab qt:

In [1]: from silx.gui.plot import *
In [2]: %pylab qt

Alternatively, when using Python 2.7 and PyQt4, you can start IPython with the QT_API environment variable set to pyqt.

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

Note

PyQt4 used from Python 2.x provides 2 incompatible versions of QString and QVariant:

  • version 1, the legacy version which is also the default, and
  • version 2, a more pythonic one, which is the only one supported by silx.

All other configurations (i.e., PyQt4 on Python 3.x, PySide, PyQt5, IPython QtConsole widget) uses version 2.

For more information, see IPython, PyQt and PySide.

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 (PyQt4, PySide or PyQt5). 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.plot.Colormap 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.plot.Colormap 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.