PyQtGraph’s Helper Functions — pyqtgraph 0.11.0rc0 documentation

# PyQtGraph’s Helper Functions

## Simple Data Display Functions

`pyqtgraph.` `plot`(*args, **kargs)

  Create and return a `PlotWindow` (this is just a window with `PlotWidget` inside), plot data in it. Accepts a title argument to set the title of the window. All other arguments are used to plot data. (see `PlotItem.plot()`)

`pyqtgraph.` `image`(*args, **kargs)

  Create and return an `ImageWindow` (this is just a window with `ImageView` widget inside), show image data inside. 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. (see `ImageView.setImage()`)

`pyqtgraph.` `dbg`(*args, **kwds)

  Create a console window and begin watching for exceptions.

  All arguments are passed to `ConsoleWidget.__init__()`.

## 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)

  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 0-255
  (R, G, B, [A]) | tuple of integers 0-255
  float | greyscale, 0.0-1.0
  int | see `intColor()`
  (int, hues) | see `intColor()`
  “RGB” | hexadecimal strings; may begin with ‘#’
  “RGBA” |
  “RRGGBB” |
  “RRGGBBAA” |
  QColor | QColor instance; makes a copy.

`pyqtgraph.` `mkPen`(*args, **kargs)

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

  Generate a QColor from HSVa values. (all arguments are float 0.0-1.0)

`pyqtgraph.` `intColor`(index, hues=9, values=1, maxValue=255, minValue=150, maxHue=360, minHue=0, sat=255, alpha=255)

  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.` `colorTuple`(c)

  Return a tuple (R,G,B,A) from a QColor

`pyqtgraph.` `colorStr`(c)

  Generate a hex string code from a QColor

`pyqtgraph.` `glColor`(*args, **kargs)

  Convert a color to OpenGL color format (r,g,b,a) floats 0.0-1.0 Accepts same arguments as `mkColor`.

## Data Slicing

`pyqtgraph.` `affineSlice`(data, shape, origin, vectors, axes, order=1, returnCoords=False, **kargs)

  Take a slice of any orientation through an array. This is useful for extracting sections of multi-dimensional 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 diagonal-planar 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)

  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)

  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.

`pyqtgraph.` `solve3DTransform`(points1, points2)

  Find a 3D transformation matrix that maps points1 onto points2. Points must be specified as either lists of 4 Vectors or (4, 3) arrays.

`pyqtgraph.` `solveBilinearTransform`(points1, points2)

  Find a bilinear transformation matrix (2x4) that maps points1 onto points2. Points must be specified as a list of 4 Vector, Point, QPointF, etc.

  To use this matrix to map a point [x,y]:

      mapped = np.dot(matrix, [x*y, x, y, 1])

## SI Unit Conversion Functions

`pyqtgraph.` `siFormat`(x, precision=3, suffix='', space=True, error=None, minVal=1e-25, allowUnicode=True)

  Return the number x formatted in engineering notation with SI prefix.

  Example::

    siFormat(0.0001, suffix=’V’) # returns “100 μV”

`pyqtgraph.` `siScale`(x, minVal=1e-25, allowUnicode=True)

  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+)?)\\s*((?P<siPrefix>[uyzafpnµm kMGTPEZY]?)(?P<suffix>\\w.*))?$'), suffix=None)

  Convert a value written in SI notation to its equivalent prefixless value.

  Example:

      siEval("100 μV")  # returns 0.0001

## Image Preparation Functions

`pyqtgraph.` `makeARGB`(data, lut=None, levels=None, scale=None, useRGBA=False)

  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:

  > 1. Rescale the data based on the values in the levels argument (min, max).

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

  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 (width, height, 3 or 4) and dtype=ubyte. The order of values in the 3rd axis must be (b, g, r, a).
  alpha | If 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)

  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.

`pyqtgraph.` `rescaleData`(data, scale, offset, dtype=None, clip=None)

  Return data rescaled and optionally cast to a new dtype:

  data => (data-offset) * scale

`pyqtgraph.` `imageToArray`(img, copy=False, transpose=True)

  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)

  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)

  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 per-face vertex indexes (Nf, 3)

## Miscellaneous Functions

`pyqtgraph.` `eq`(a, b)

  The great missing equivalence function: Guaranteed evaluation to a single bool value.

  This function has some important differences from the == operator:

  1. Returns True if a IS b, even if a==b still evaluates to False, such as with nan values.

  2. Tests for equivalence using ==, but silently ignores some common exceptions that can occur (AtrtibuteError, ValueError).

  3. When comparing arrays, returns False if the array shapes are not the same.

  4. When comparing arrays of the same shape, returns True only if all elements are equal (whereas the == operator would return a boolean array).

  5. 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')

  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)

  Used for examining the distribution of values in a set. Produces scattering as in beeswarm or column scatter plots.

  Given a list of x-values, construct a set of y-values such that an x,y scatter-plot will not have overlapping points (it will look similar to a histogram).

`pyqtgraph.` `systemInfo`()

`pyqtgraph.` `exit`()

  Causes python to exit without garbage-collecting 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.