PyQtGraph’s Helper Functions¶
Simple Data Display Functions¶

pyqtgraph.
plot
(*args, **kargs)[source]¶ Create and return a
PlotWidget
Accepts a title argument to set the title of the window. All other arguments are used to plot data. (seePlotItem.plot()
)

pyqtgraph.
image
(*args, **kargs)[source]¶ Create and return an
ImageView
Will show 2D or 3D image data. Accepts a title argument to set the title of the window. All other arguments are used to show data. (seeImageView.setImage()
)
Color, Pen, and Brush Functions¶
Qt uses the classes QColor, QPen, and QBrush to determine how to draw lines and fill shapes. These classes are highly capable but somewhat awkward to use. PyQtGraph offers the functions mkColor()
, mkPen()
, and mkBrush()
to simplify the process of creating these classes. In most cases, however, it will be unnecessary to call these functions directly–any function or method that accepts pen or brush arguments will make use of these functions for you. For example, the following three lines all have the same effect:
pg.plot(xdata, ydata, pen='r')
pg.plot(xdata, ydata, pen=pg.mkPen('r'))
pg.plot(xdata, ydata, pen=QPen(QColor(255, 0, 0)))

pyqtgraph.
mkColor
(*args)[source]¶ Convenience function for constructing QColor from a variety of argument types. Accepted arguments are:
‘c’
one of: r, g, b, c, m, y, k, w
R, G, B, [A]
integers 0255
(R, G, B, [A])
tuple of integers 0255
float
greyscale, 0.01.0
int
see
intColor()
(int, hues)
see
intColor()
“#RGB”
hexadecimal strings prefixed with ‘#’
“#RGBA”
previously allowed use without prefix is deprecated and
“#RRGGBB”
will be removed in 0.13
“#RRGGBBAA”
QColor
QColor instance; makes a copy.

pyqtgraph.
mkPen
(*args, **kargs)[source]¶ Convenience function for constructing QPen.
Examples:
mkPen(color) mkPen(color, width=2) mkPen(cosmetic=False, width=4.5, color='r') mkPen({'color': "#FF0", width: 2}) mkPen(None) # (no pen)
In these examples, color may be replaced with any arguments accepted by
mkColor()

pyqtgraph.
mkBrush
(*args, **kwds)[source]¶  Convenience function for constructing Brush.This function always constructs a solid brush and accepts the same arguments as
mkColor()
Calling mkBrush(None) returns an invisible brush.

pyqtgraph.
hsvColor
(hue, sat=1.0, val=1.0, alpha=1.0)[source]¶ Generate a QColor from HSVa values. (all arguments are float 0.01.0)

pyqtgraph.
intColor
(index, hues=9, values=1, maxValue=255, minValue=150, maxHue=360, minHue=0, sat=255, alpha=255)[source]¶ Creates a QColor from a single index. Useful for stepping through a predefined list of colors.
The argument index determines which color from the set will be returned. All other arguments determine what the set of predefined colors will be
Colors are chosen by cycling across hues while varying the value (brightness). By default, this selects from a list of 9 hues.
Data Slicing¶

pyqtgraph.
affineSlice
(data, shape, origin, vectors, axes, order=1, returnCoords=False, **kargs)[source]¶ Take a slice of any orientation through an array. This is useful for extracting sections of multidimensional arrays such as MRI images for viewing as 1D or 2D data.
The slicing axes are aribtrary; they do not need to be orthogonal to the original data or even to each other. It is possible to use this function to extract arbitrary linear, rectangular, or parallelepiped shapes from within larger datasets. The original data is interpolated onto a new array of coordinates using either interpolateArray if order<2 or scipy.ndimage.map_coordinates otherwise.
For a graphical interface to this function, see
ROI.getArrayRegion
Arguments:
data
(ndarray) the original dataset
shape
the shape of the slice to take (Note the return value may have more dimensions than len(shape))
origin
the location in the original dataset that will become the origin of the sliced data.
vectors
list of unit vectors which point in the direction of the slice axes. Each vector must have the same length as axes. If the vectors are not unit length, the result will be scaled relative to the original data. If the vectors are not orthogonal, the result will be sheared relative to the original data.
axes
The axes in the original dataset which correspond to the slice vectors
order
The order of spline interpolation. Default is 1 (linear). See scipy.ndimage.map_coordinates for more information.
returnCoords
If True, return a tuple (result, coords) where coords is the array of coordinates used to select values from the original dataset.
All extra keyword arguments are passed to scipy.ndimage.map_coordinates.
Note the following must be true:
len(shape) == len(vectors)len(origin) == len(axes) == len(vectors[i])Example: start with a 4D fMRI data set, take a diagonalplanar slice out of the last 3 axes
data = array with dims (time, x, y, z) = (100, 40, 40, 40)
The plane to pull out is perpendicular to the vector (x,y,z) = (1,1,1)
The origin of the slice will be at (x,y,z) = (40, 0, 0)
We will slice a 20x20 plane from each timepoint, giving a final shape (100, 20, 20)
The call for this example would look like:
affineSlice(data, shape=(20,20), origin=(40,0,0), vectors=((1, 1, 0), (1, 0, 1)), axes=(1,2,3))
Coordinate Transformation¶

pyqtgraph.
transformToArray
(tr)[source]¶ Given a QTransform, return a 3x3 numpy array. Given a QMatrix4x4, return a 4x4 numpy array.
Example: map an array of x,y coordinates through a transform:
## coordinates to map are (1,5), (2,6), (3,7), and (4,8) coords = np.array([[1,2,3,4], [5,6,7,8], [1,1,1,1]]) # the extra '1' coordinate is needed for translation to work ## Make an example transform tr = QtGui.QTransform() tr.translate(3,4) tr.scale(2, 0.1) ## convert to array m = pg.transformToArray()[:2] # ignore the perspective portion of the transformation ## map coordinates through transform mapped = np.dot(m, coords)

pyqtgraph.
transformCoordinates
(tr, coords, transpose=False)[source]¶ Map a set of 2D or 3D coordinates through a QTransform or QMatrix4x4. The shape of coords must be (2,…) or (3,…) The mapping will _ignore_ any perspective transformations.
For coordinate arrays with ndim=2, this is basically equivalent to matrix multiplication. Most arrays, however, prefer to put the coordinate axis at the end (eg. shape=(…,3)). To allow this, use transpose=True.
SI Unit Conversion Functions¶

pyqtgraph.
siFormat
(x, precision=3, suffix='', space=True, error=None, minVal=1e25, allowUnicode=True)[source]¶ Return the number x formatted in engineering notation with SI prefix.
 Example::
siFormat(0.0001, suffix=’V’) # returns “100 μV”

pyqtgraph.
siScale
(x, minVal=1e25, allowUnicode=True)[source]¶ Return the recommended scale factor and SI prefix string for x.
Example:
siScale(0.0001) # returns (1e6, 'μ') # This indicates that the number 0.0001 is best represented as 0.0001 * 1e6 = 100 μUnits

pyqtgraph.
siEval
(s, typ=<class 'float'>, regex=re.compile('(?P<number>[+]?((((\\d+(\\.\\d*)?)(\\d*\\.\\d+))([eE][+]?\\d+)?)((?i:nan)(inf))))\\s*((?P<siPrefix>[uyzafpnµm kMGTPEZY]?)(?P<suffix>\\w.*))?$'), suffix=None)[source]¶ Convert a value written in SI notation to its equivalent prefixless value.
Example:
siEval("100 μV") # returns 0.0001

pyqtgraph.
siParse
(s, regex=re.compile('(?P<number>[+]?((((\\d+(\\.\\d*)?)(\\d*\\.\\d+))([eE][+]?\\d+)?)((?i:nan)(inf))))\\s*((?P<siPrefix>[uyzafpnµm kMGTPEZY]?)(?P<suffix>\\w.*))?$'), suffix=None)[source]¶ Convert a value written in SI notation to a tuple (number, si_prefix, suffix).
Example:
siParse('100 µV") # returns ('100', 'µ', 'V')
Note that in the above example, the µ symbol is the “micro sign” (UTF8 0xC2B5), as opposed to the Greek letter mu (UTF8 0xCEBC).
 Parameters
s (str) – The string to parse.
regex (re.Pattern, optional) – Compiled regular expression object for parsing. The default is a generalpurpose regex for parsing floating point expressions, potentially containing an SI prefix and a suffix.
suffix (str, optional) – Suffix to check for in
s
. The default (None) indicates there may or may not be a suffix contained in the string and it is returned if found. An empty string""
is handled differently: if the string contains a suffix, it is discarded. This enables interpreting characters following the numerical value as an SI prefix.
Image Preparation Functions¶

pyqtgraph.
makeARGB
(data, lut=None, levels=None, scale=None, useRGBA=False, output=None)[source]¶ Convert an array of values into an ARGB array suitable for building QImages, OpenGL textures, etc.
Returns the ARGB array (unsigned byte) and a boolean indicating whether there is alpha channel data. This is a two stage process:
Rescale the data based on the values in the levels argument (min, max).
Determine the final output by passing the rescaled values through a lookup table.
Both stages are optional.
Arguments:
data
numpy array of int/float types. If
levels
List [min, max]; optionally rescale data before converting through the lookup table. The data is rescaled such that min>0 and max>*scale*:
rescaled = (clip(data, min, max)  min) * (*scale* / (max  min))
It is also possible to use a 2D (N,2) array of values for levels. In this case, it is assumed that each pair of min,max values in the levels array should be applied to a different subset of the input data (for example, the input data may already have RGB values and the levels are used to independently scale each channel). The use of this feature requires that levels.shape[0] == data.shape[1].
scale
The maximum value to which data will be rescaled before being passed through the lookup table (or returned if there is no lookup table). By default this will be set to the length of the lookup table, or 255 if no lookup table is provided.
lut
Optional lookup table (array with dtype=ubyte). Values in data will be converted to color by indexing directly from lut. The output data shape will be input.shape + lut.shape[1:]. Lookup tables can be built using ColorMap or GradientWidget.
useRGBA
If True, the data is returned in RGBA order (useful for building OpenGL textures). The default is False, which returns in ARGB order for use with QImage (Note that ‘ARGB’ is a term used by the Qt documentation; the actual order is BGRA).

pyqtgraph.
makeQImage
(imgData, alpha=None, copy=True, transpose=True)[source]¶ Turn an ARGB array into QImage. By default, the data is copied; changes to the array will not be reflected in the image. The image will be given a ‘data’ attribute pointing to the array which shares its data to prevent python freeing that memory while the image is in use.
Arguments:
imgData
Array of data to convert. Must have shape (height, width), (height, width, 3), or (height, width, 4). If transpose is True, then the first two axes are swapped. The array dtype must be ubyte. For 2D arrays, the value is interpreted as greyscale. For 3D arrays, the order of values in the 3rd axis must be (b, g, r, a).
alpha
If the input array is 3D and alpha is True, the QImage returned will have format ARGB32. If False, the format will be RGB32. By default, _alpha_ is True if array.shape[2] == 4.
copy
If True, the data is copied before converting to QImage. If False, the new QImage points directly to the data in the array. Note that the array must be contiguous for this to work (see numpy.ascontiguousarray).
transpose
If True (the default), the array x/y axes are transposed before creating the image. Note that Qt expects the axes to be in (height, width) order whereas pyqtgraph usually prefers the opposite.

pyqtgraph.
applyLookupTable
(data, lut)[source]¶ Uses values in data as indexes to select values from lut. The returned data has shape data.shape + lut.shape[1:]
Note: color gradient lookup tables can be generated using GradientWidget.
 Parameters
data (ndarray) –
lut (ndarray) – Either cupy or numpy arrays are accepted, though this function has only consistently behaved correctly on windows with cuda toolkit version >= 11.1.

pyqtgraph.
rescaleData
(data, scale, offset, dtype=None, clip=None)[source]¶ Return data rescaled and optionally cast to a new dtype.
The scaling operation is:
data => (dataoffset) * scale

pyqtgraph.
imageToArray
(img, copy=False, transpose=True)[source]¶ Convert a QImage into numpy array. The image must have format RGB32, ARGB32, or ARGB32_Premultiplied. By default, the image is not copied; changes made to the array will appear in the QImage as well (beware: if the QImage is collected before the array, there may be trouble). The array will have shape (width, height, (b,g,r,a)).
Mesh Generation Functions¶

pyqtgraph.
isocurve
(data, level, connected=False, extendToEdge=False, path=False)[source]¶ Generate isocurve from 2D data using marching squares algorithm.
Arguments:
data
2D numpy array of scalar values
level
The level at which to generate an isosurface
connected
If False, return a single long list of point pairs If True, return multiple long lists of connected point locations. (This is slower but better for drawing continuous lines)
extendToEdge
If True, extend the curves to reach the exact edges of the data.
path
if True, return a QPainterPath rather than a list of vertex coordinates. This forces connected=True.
This function is SLOW; plenty of room for optimization here.

pyqtgraph.
isosurface
(data, level)[source]¶ Generate isosurface from volumetric data using marching cubes algorithm. See Paul Bourke, “Polygonising a Scalar Field” (http://paulbourke.net/geometry/polygonise/)
data 3D numpy array of scalar values. Must be contiguous. level The level at which to generate an isosurface
Returns an array of vertex coordinates (Nv, 3) and an array of perface vertex indexes (Nf, 3)
Miscellaneous Functions¶

pyqtgraph.
eq
(a, b)[source]¶ The great missing equivalence function: Guaranteed evaluation to a single bool value.
This function has some important differences from the == operator:
Returns True if a IS b, even if a==b still evaluates to False.
While a is b will catch the case with np.nan values, special handling is done for distinct float(‘nan’) instances using np.isnan.
Tests for equivalence using ==, but silently ignores some common exceptions that can occur (AtrtibuteError, ValueError).
When comparing arrays, returns False if the array shapes are not the same.
When comparing arrays of the same shape, returns True only if all elements are equal (whereas the == operator would return a boolean array).
Collections (dict, list, etc.) must have the same type to be considered equal. One consequence is that comparing a dict to an OrderedDict will always return False.

pyqtgraph.
arrayToQPath
(x, y, connect='all')[source]¶ Convert an array of x,y coordinats to QPainterPath as efficiently as possible. The connect argument may be ‘all’, indicating that each point should be connected to the next; ‘pairs’, indicating that each pair of points should be connected, or an array of int32 values (0 or 1) indicating connections.

pyqtgraph.
pseudoScatter
(data, spacing=None, shuffle=True, bidir=False, method='exact')[source]¶ Return an array of position values needed to make beeswarm or column scatter plots.
Used for examining the distribution of values in an array.
Given an array of xvalues, construct an array of yvalues such that an x,y scatterplot will not have overlapping points (it will look similar to a histogram).

pyqtgraph.
exit
()[source]¶ Causes python to exit without garbagecollecting any objects, and thus avoids calling object destructor methods. This is a sledgehammer workaround for a variety of bugs in PyQt and Pyside that cause crashes on exit.
This function does the following in an attempt to ‘safely’ terminate the process:
Invoke atexit callbacks
Close all open file handles
os._exit()
Note: there is some potential for causing damage with this function if you are using objects that _require_ their destructors to be called (for example, to properly terminate log files, disconnect from devices, etc). Situations like this are probably quite rare, but use at your own risk.