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.

pyqtgraph.
CIELabColor
(L, a, b, alpha=1.0)[source]¶ Generates as QColor from CIE L*a*b* values.
 Parameters
L (float) – Lightness value ranging from 0 to 100
a (float) – (green/red) and (blue/yellow) coordinates, typically 127 to +127.
b (float) – (green/red) and (blue/yellow) coordinates, typically 127 to +127.
alpha (float, optional) – Opacity, ranging from 0 to 1
Notes
The CIE L*a*b* color space parametrizes color in terms of a luminance L and the a and b coordinates that locate the hue in terms of a “green to red” and a “blue to yellow” axis.
These coordinates seek to parametrize human color preception in such a way that the Euclidean distance between the coordinates of two colors represents the visual difference between these colors. In particular, the difference
ΔE = sqrt( (L1L2)² + (a1a2)² + (b1b2)² ) = 2.3
is considered the smallest “just noticeable difference” between colors.
This simple equation represents the CIE76 standard. Later standards CIE94 and CIE2000 refine the difference calculation ΔE, while maintaining the L*a*b* coordinates.
Alternative (and arguably more accurate) methods exist to quantify color difference, but the CIELab color space remains a convenient approximation.
Under a known illumination, assumed to be white standard illuminant D65 here, a CIELab color induces a response in the human eye that is described by the tristimulus value XYZ. Once this is known, an sRGB color can be calculated to induce the same response.
More information and underlying mathematics can be found in e.g. “CIELab Color Space” by Gernot Hoffmann, available at http://docshoffmann.de/cielab03022003.pdf .
Also see
colorDistance()
.

pyqtgraph.
colorCIELab
(qcol)[source]¶ Describes a QColor by an array of CIE L*a*b* values. Also see
CIELabColor()
. Parameters
qcol (QColor) – QColor to be converted
 Returns
Color coordinates [L, a, b].
 Return type
NumPy array

pyqtgraph.
glColor
(*args, **kargs)[source]¶ Convert a color to OpenGL color format (r,g,b,a) floats 0.01.0 Accepts same arguments as
mkColor
.

pyqtgraph.
colorDistance
(colors, metric='CIE76')[source]¶ Returns the perceptual distances between a sequence of QColors. See
CIELabColor()
for more information. Parameters
colors (list of QColor) – Two or more colors to calculate the distances between.
metric (string, optional) – Metric used to determined the difference. Only ‘CIE76’ is supported at this time, where a distance of 2.3 is considered a “just noticeable difference”. The default may change as more metrics become available.
 Returns
The N1 sequential distances between N colors.
 Return type
List
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 math.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', finiteCheck=True)[source]¶ Convert an array of x,y coordinates 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.
 Parameters
x ((N,) ndarray) – xvalues to be plotted
y ((N,) ndarray) – yvalues to be plotted, must be same length as x
connect ({'all', 'pairs', 'finite', (N,) ndarray}, optional) – Argument detailing how to connect the points in the path. all will have sequential points being connected. pairs generates lines between every other point. finite only connects points that are finite. If an ndarray is passed, containing int32 values of 0 or 1, only values with 1 will connect to the previous point. Def
finiteCheck (bool, default Ture) – When false, the check for finite values will be skipped, which can improve performance. If finite values are present in x or y, an empty QPainterPath will be generated.
 Returns
QPainterPath object to be drawn
 Return type
QPainterPath
 Raises
ValueError – Raised when the connect argument has an invalid value placed within.
Notes
A QPainterPath is generated through one of two ways. When the connect parameter is ‘all’, a QPolygonF object is created, and
QPainterPath.addPolygon()
is called. For other connect parameters aQDataStream
object is created and the QDataStream >> QPainterPath operator is used to pass the data. The memory format is as followsnumVerts(i4) 0(i4) x(f8) y(f8) <– 0 means this vertex does not connect 1(i4) x(f8) y(f8) <– 1 means this vertex connects to the previous vertex … cStart(i4) fillRule(i4)
see: https://github.com/qt/qtbase/blob/dev/src/gui/painting/qpainterpath.cpp
All values are big endian–pack using struct.pack(‘>d’) or struct.pack(‘>i’) This binary format may change in future versions of Qt

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.