desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'**Arguments:** data Volume data to be rendered. *Must* be 3D numpy array (x, y, RGBA) with dtype=ubyte. (See functions.makeRGBA) smooth (bool) If True, the volume slices are rendered with linear interpolation'
def __init__(self, data, smooth=False, glOptions='translucent'):
self.smooth = smooth self._needUpdate = False GLGraphicsItem.__init__(self) self.setData(data) self.setGLOptions(glOptions)
'**Arguments:** data Volume data to be rendered. *Must* be 4D numpy array (x, y, z, RGBA) with dtype=ubyte. sliceDensity Density of slices to render through the volume. A value of 1 means one slice per voxel. smooth (bool) If True, the volume slices are rendered with linear interpolation'
def __init__(self, data, sliceDensity=1, smooth=True, glOptions='translucent'):
self.sliceDensity = sliceDensity self.smooth = smooth self.data = None self._needUpload = False self.texture = None GLGraphicsItem.__init__(self) self.setGLOptions(glOptions) self.setData(data)
'Set the size of the box (in its local coordinate system; this does not affect the transform) Arguments can be x,y,z or size=QVector3D().'
def setSize(self, x=None, y=None, z=None, size=None):
if (size is not None): x = size.x() y = size.y() z = size.z() self.__size = [x, y, z] self.update()
'Set the color of the box. Arguments are the same as those accepted by functions.mkColor()'
def setColor(self, *args):
self.__color = fn.Color(*args)
'The x, y, z, and colors arguments are passed to setData(). All other keyword arguments are passed to GLMeshItem.__init__().'
def __init__(self, x=None, y=None, z=None, colors=None, **kwds):
self._x = None self._y = None self._z = None self._color = None self._vertexes = None self._meshdata = MeshData() GLMeshItem.__init__(self, meshdata=self._meshdata, **kwds) self.setData(x, y, z, colors)
'Update the data in this surface plot. **Arguments:** x,y 1D arrays of values specifying the x,y positions of vertexes in the grid. If these are omitted, then the values will be assumed to be integers. z 2D array of height values for each grid vertex. colors (width, height, 4) array of vertex colors. All arguments are optional. Note that if vertex positions are updated, the normal vectors for each triangle must be recomputed. This is somewhat expensive if the surface was initialized with smooth=False and very expensive if smooth=True. For faster performance, initialize with computeNormals=False and use per-vertex colors or a normal-independent shader program.'
def setData(self, x=None, y=None, z=None, colors=None):
if (x is not None): if ((self._x is None) or (len(x) != len(self._x))): self._vertexes = None self._x = x if (y is not None): if ((self._y is None) or (len(y) != len(self._y))): self._vertexes = None self._y = y if (z is not None): if ((self._x is not None) and (z.shape[0] != len(self._x))): raise Exception('Z values must have shape (len(x), len(y))') if ((self._y is not None) and (z.shape[1] != len(self._y))): raise Exception('Z values must have shape (len(x), len(y))') self._z = z if ((self._vertexes is not None) and (self._z.shape != self._vertexes.shape[:2])): self._vertexes = None if (colors is not None): self._colors = colors self._meshdata.setVertexColors(colors) if (self._z is None): return updateMesh = False newVertexes = False if (self._vertexes is None): newVertexes = True self._vertexes = np.empty((self._z.shape[0], self._z.shape[1], 3), dtype=float) self.generateFaces() self._meshdata.setFaces(self._faces) updateMesh = True if (newVertexes or (x is not None)): if (x is None): if (self._x is None): x = np.arange(self._z.shape[0]) else: x = self._x self._vertexes[:, :, 0] = x.reshape(len(x), 1) updateMesh = True if (newVertexes or (y is not None)): if (y is None): if (self._y is None): y = np.arange(self._z.shape[1]) else: y = self._y self._vertexes[:, :, 1] = y.reshape(1, len(y)) updateMesh = True if (newVertexes or (z is not None)): self._vertexes[..., 2] = self._z updateMesh = True if updateMesh: self._meshdata.setVertexes(self._vertexes.reshape((self._vertexes.shape[0] * self._vertexes.shape[1]), 3)) self.meshDataChanged()
'Update the data displayed by this item. All arguments are optional; for example it is allowed to update spot positions while leaving colors unchanged, etc. **Arguments:** pos (N,3) array of floats specifying point locations. color (N,4) array of floats (0.0-1.0) specifying spot colors OR a tuple of floats specifying a single color for all spots. size (N,) array of floats specifying spot sizes or a single value to apply to all spots. pxMode If True, spot sizes are expressed in pixels. Otherwise, they are expressed in item coordinates.'
def setData(self, **kwds):
args = ['pos', 'color', 'size', 'pxMode'] for k in kwds.keys(): if (k not in args): raise Exception(('Invalid keyword argument: %s (allowed arguments are %s)' % (k, str(args)))) args.remove('pxMode') for arg in args: if (arg in kwds): setattr(self, arg, kwds[arg]) self.pxMode = kwds.get('pxMode', self.pxMode) self.update()
'All keyword arguments are passed to setData()'
def __init__(self, **kwds):
GLGraphicsItem.__init__(self) glopts = kwds.pop('glOptions', 'additive') self.setGLOptions(glopts) self.pos = None self.mode = 'line_strip' self.width = 1.0 self.color = (1.0, 1.0, 1.0, 1.0) self.setData(**kwds)
'Update the data displayed by this item. All arguments are optional; for example it is allowed to update vertex positions while leaving colors unchanged, etc. **Arguments:** pos (N,3) array of floats specifying point locations. color (N,4) array of floats (0.0-1.0) or tuple of floats specifying a single color for the entire item. width float specifying line width antialias enables smooth line drawing mode \'lines\': Each pair of vertexes draws a single line segment. \'line_strip\': All vertexes are drawn as a continuous set of line segments.'
def setData(self, **kwds):
args = ['pos', 'color', 'width', 'mode', 'antialias'] for k in kwds.keys(): if (k not in args): raise Exception(('Invalid keyword argument: %s (allowed arguments are %s)' % (k, str(args)))) self.antialias = False for arg in args: if (arg in kwds): setattr(self, arg, kwds[arg]) self.update()
'**Arguments:** meshdata MeshData object from which to determine geometry for this item. color Default face color used if no vertex or face colors are specified. edgeColor Default edge color to use if no edge colors are specified in the mesh data. drawEdges If True, a wireframe mesh will be drawn. (default=False) drawFaces If True, mesh faces are drawn. (default=True) shader Name of shader program to use when drawing faces. (None for no shader) smooth If True, normal vectors are computed for each vertex and interpolated within each face. computeNormals If False, then computation of normal vectors is disabled. This can provide a performance boost for meshes that do not make use of normals.'
def __init__(self, **kwds):
self.opts = {'meshdata': None, 'color': (1.0, 1.0, 1.0, 1.0), 'drawEdges': False, 'drawFaces': True, 'edgeColor': (0.5, 0.5, 0.5, 1.0), 'shader': None, 'smooth': True, 'computeNormals': True} GLGraphicsItem.__init__(self) glopts = kwds.pop('glOptions', 'opaque') self.setGLOptions(glopts) shader = kwds.pop('shader', None) self.setShader(shader) self.setMeshData(**kwds) self.vertexes = None self.normals = None self.colors = None self.faces = None
'Set the shader used when rendering faces in the mesh. (see the GL shaders example)'
def setShader(self, shader):
self.opts['shader'] = shader self.update()
'Set the default color to use when no vertex or face colors are specified.'
def setColor(self, c):
self.opts['color'] = c self.update()
'Set mesh data for this item. This can be invoked two ways: 1. Specify *meshdata* argument with a new MeshData object 2. Specify keyword arguments to be passed to MeshData(..) to create a new instance.'
def setMeshData(self, **kwds):
md = kwds.get('meshdata', None) if (md is None): opts = {} for k in ['vertexes', 'faces', 'edges', 'vertexColors', 'faceColors']: try: opts[k] = kwds.pop(k) except KeyError: pass md = MeshData(**opts) self.opts['meshdata'] = md self.opts.update(kwds) self.meshDataChanged() self.update()
'This method must be called to inform the item that the MeshData object has been altered.'
def meshDataChanged(self):
self.vertexes = None self.faces = None self.normals = None self.colors = None self.edges = None self.edgeColors = None self.update()
'Set the size of the axes (in its local coordinate system; this does not affect the transform) Arguments can be x,y,z or size=QVector3D().'
def setSize(self, x=None, y=None, z=None, size=None):
if (size is not None): x = size.x() y = size.y() z = size.z() self.__size = [x, y, z] self.update()
'Set the spacing between grid lines. Arguments can be x,y,z or spacing=QVector3D().'
def setSpacing(self, x=None, y=None, z=None, spacing=None):
if (spacing is not None): x = spacing.x() y = spacing.y() z = spacing.z() self.__spacing = [x, y, z] self.update()
'pos is (...,3) array of the bar positions (the corner of each bar) size is (...,3) array of the sizes of each bar'
def __init__(self, pos, size):
nCubes = reduce((lambda a, b: (a * b)), pos.shape[:(-1)]) cubeVerts = np.mgrid[0:2, 0:2, 0:2].reshape(3, 8).transpose().reshape(1, 8, 3) cubeFaces = np.array([[0, 1, 2], [3, 2, 1], [4, 5, 6], [7, 6, 5], [0, 1, 4], [5, 4, 1], [2, 3, 6], [7, 6, 3], [0, 2, 4], [6, 4, 2], [1, 3, 5], [7, 5, 3]]).reshape(1, 12, 3) size = size.reshape((nCubes, 1, 3)) pos = pos.reshape((nCubes, 1, 3)) verts = ((cubeVerts * size) + pos) faces = (cubeFaces + (np.arange(nCubes) * 8).reshape(nCubes, 1, 1)) md = MeshData(verts.reshape((nCubes * 8), 3), faces.reshape((nCubes * 12), 3)) GLMeshItem.__init__(self, meshdata=md, shader='shaded', smooth=False)
'Set this item\'s parent in the scenegraph hierarchy.'
def setParentItem(self, item):
if (self.__parent is not None): self.__parent.__children.remove(self) if (item is not None): item.__children.add(self) self.__parent = item if ((self.__parent is not None) and (self.view() is not self.__parent.view())): if (self.view() is not None): self.view().removeItem(self) self.__parent.view().addItem(self)
'Set the OpenGL state options to use immediately before drawing this item. (Note that subclasses must call setupGLState before painting for this to work) The simplest way to invoke this method is to pass in the name of a predefined set of options (see the GLOptions variable): opaque Enables depth testing and disables blending translucent Enables depth testing and blending Elements must be drawn sorted back-to-front for translucency to work correctly. additive Disables depth testing, enables blending. Colors are added together, so sorting is not required. It is also possible to specify any arbitrary settings as a dictionary. This may consist of {\'functionName\': (args...)} pairs where functionName must be a callable attribute of OpenGL.GL, or {GL_STATE_VAR: bool} pairs which will be interpreted as calls to glEnable or glDisable(GL_STATE_VAR). For example:: GL_ALPHA_TEST: True, GL_CULL_FACE: False, \'glBlendFunc\': (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA),'
def setGLOptions(self, opts):
if isinstance(opts, basestring): opts = GLOptions[opts] self.__glOpts = opts.copy() self.update()
'Modify the OpenGL state options to use immediately before drawing this item. *opts* must be a dictionary as specified by setGLOptions. Values may also be None, in which case the key will be ignored.'
def updateGLOptions(self, opts):
self.__glOpts.update(opts)
'Return a this item\'s parent in the scenegraph hierarchy.'
def parentItem(self):
return self.__parent
'Return a list of this item\'s children in the scenegraph hierarchy.'
def childItems(self):
return list(self.__children)
'Sets the depth value of this item. Default is 0. This controls the order in which items are drawn--those with a greater depth value will be drawn later. Items with negative depth values are drawn before their parent. (This is analogous to QGraphicsItem.zValue) The depthValue does NOT affect the position of the item or the values it imparts to the GL depth buffer.'
def setDepthValue(self, value):
self.__depthValue = value
'Return the depth value of this item. See setDepthValue for more information.'
def depthValue(self):
return self.__depthValue
'Set the local transform for this object. Must be a :class:`Transform3D <pyqtgraph.Transform3D>` instance. This transform determines how the local coordinate system of the item is mapped to the coordinate system of its parent.'
def setTransform(self, tr):
self.__transform = Transform3D(tr) self.update()
'Reset this item\'s transform to an identity transformation.'
def resetTransform(self):
self.__transform.setToIdentity() self.update()
'Multiply this object\'s transform by *tr*. If local is True, then *tr* is multiplied on the right of the current transform:: newTransform = transform * tr If local is False, then *tr* is instead multiplied on the left:: newTransform = tr * transform'
def applyTransform(self, tr, local):
if local: self.setTransform((self.transform() * tr)) else: self.setTransform((tr * self.transform()))
'Return this item\'s transform object.'
def transform(self):
return self.__transform
'Return the transform mapping this item\'s local coordinate system to the view coordinate system.'
def viewTransform(self):
tr = self.__transform p = self while True: p = p.parentItem() if (p is None): break tr = (p.transform() * tr) return Transform3D(tr)
'Translate the object by (*dx*, *dy*, *dz*) in its parent\'s coordinate system. If *local* is True, then translation takes place in local coordinates.'
def translate(self, dx, dy, dz, local=False):
tr = Transform3D() tr.translate(dx, dy, dz) self.applyTransform(tr, local=local)
'Rotate the object around the axis specified by (x,y,z). *angle* is in degrees.'
def rotate(self, angle, x, y, z, local=False):
tr = Transform3D() tr.rotate(angle, x, y, z) self.applyTransform(tr, local=local)
'Scale the object by (*dx*, *dy*, *dz*) in its local coordinate system. If *local* is False, then scale takes place in the parent\'s coordinates.'
def scale(self, x, y, z, local=True):
tr = Transform3D() tr.scale(x, y, z) self.applyTransform(tr, local=local)
'Hide this item. This is equivalent to setVisible(False).'
def hide(self):
self.setVisible(False)
'Make this item visible if it was previously hidden. This is equivalent to setVisible(True).'
def show(self):
self.setVisible(True)
'Set the visibility of this item.'
def setVisible(self, vis):
self.__visible = vis self.update()
'Return True if the item is currently set to be visible. Note that this does not guarantee that the item actually appears in the view, as it may be obscured or outside of the current view area.'
def visible(self):
return self.__visible
'Called after an item is added to a GLViewWidget. The widget\'s GL context is made current before this method is called. (So this would be an appropriate time to generate lists, upload textures, etc.)'
def initializeGL(self):
pass
'This method is responsible for preparing the GL state options needed to render this item (blending, depth testing, etc). The method is called immediately before painting the item.'
def setupGLState(self):
for (k, v) in self.__glOpts.items(): if (v is None): continue if isinstance(k, basestring): func = getattr(GL, k) func(*v) elif (v is True): glEnable(k) else: glDisable(k)
'Called by the GLViewWidget to draw this item. It is the responsibility of the item to set up its own modelview matrix, but the caller will take care of pushing/popping.'
def paint(self):
self.setupGLState()
'Indicates that this item needs to be redrawn, and schedules an update with the view it is displayed in.'
def update(self):
v = self.view() if (v is None): return v.update()
'Return list of all selected canvasItems'
def selectedItems(self):
return [item.canvasItem() for item in self.itemList.selectedItems() if (item.canvasItem() is not None)]
'Add a new GraphicsItem to the scene at pos. Common options are name, pos, scale, and z'
def addGraphicsItem(self, item, **opts):
citem = CanvasItem(item, **opts) item._canvasItem = citem self.addItem(citem) return citem
'Add an item to the canvas.'
def addItem(self, citem):
if (self.redirect is not None): name = self.redirect.addItem(citem) self.items.append(citem) return name if (not self.allowTransforms): citem.setMovable(False) citem.sigTransformChanged.connect(self.itemTransformChanged) citem.sigTransformChangeFinished.connect(self.itemTransformChangeFinished) citem.sigVisibilityChanged.connect(self.itemVisibilityChanged) name = citem.opts['name'] if (name is None): name = 'item' newname = name insertLocation = 0 parent = citem.parentItem() if (parent in (None, self.view.childGroup)): parent = self.itemList.invisibleRootItem() else: parent = parent.listItem siblings = [parent.child(i).canvasItem() for i in range(parent.childCount())] z = citem.zValue() if (z is None): zvals = [i.zValue() for i in siblings] if (parent is self.itemList.invisibleRootItem()): if (len(zvals) == 0): z = 0 else: z = (max(zvals) + 10) elif (len(zvals) == 0): z = parent.canvasItem().zValue() else: z = (max(zvals) + 1) citem.setZValue(z) for i in range(parent.childCount()): ch = parent.child(i) zval = ch.canvasItem().graphicsItem().zValue() if (zval < z): insertLocation = i break else: insertLocation = (i + 1) node = QtGui.QTreeWidgetItem([name]) flags = ((node.flags() | QtCore.Qt.ItemIsUserCheckable) | QtCore.Qt.ItemIsDragEnabled) if (not isinstance(citem, GroupCanvasItem)): flags = (flags & (~ QtCore.Qt.ItemIsDropEnabled)) node.setFlags(flags) if citem.opts['visible']: node.setCheckState(0, QtCore.Qt.Checked) else: node.setCheckState(0, QtCore.Qt.Unchecked) node.name = name parent.insertChild(insertLocation, node) citem.name = name citem.listItem = node node.canvasItem = weakref.ref(citem) self.items.append(citem) ctrl = citem.ctrlWidget() ctrl.hide() self.ui.ctrlLayout.addWidget(ctrl) citem.setCanvas(self) if (len(self.items) == 2): self.autoRange() return citem
'Return a dictionary of name:item pairs'
def listItems(self):
return self.items
'Return the graphicsItem for this canvasItem.'
def graphicsItem(self):
return self._graphicsItem
'The selection box has moved; get its transformation information and pass to the graphics item'
def selectBoxMoved(self):
self.userTransform = self.selectBox.getGlobalTransform(relativeTo=self.selectBoxBase) self.updateTransform()
'Collapses tempTransform into UserTransform, resets tempTransform'
def applyTemporaryTransform(self):
self.userTransform = (self.userTransform * self.tempTransform) self.resetTemporaryTransform() self.selectBoxFromUser()
'Regenerate the item position from the base, user, and temp transforms'
def updateTransform(self):
transform = ((self.baseTransform * self.userTransform) * self.tempTransform) s = transform.saveState() self._graphicsItem.setPos(*s['pos']) self.itemRotation.setAngle(s['angle']) self.itemScale.setXScale(s['scale'][0]) self.itemScale.setYScale(s['scale'][1]) self.displayTransform(transform) return s
'Updates transform numbers in the ctrl widget.'
def displayTransform(self, transform):
tr = transform.saveState() self.transformGui.translateLabel.setText(('Translate: (%f, %f)' % (tr['pos'][0], tr['pos'][1]))) self.transformGui.rotateLabel.setText(('Rotate: %f degrees' % tr['angle'])) self.transformGui.scaleLabel.setText(('Scale: (%f, %f)' % (tr['scale'][0], tr['scale'][1])))
'Return a dict containing the current user transform'
def saveTransform(self):
return self.userTransform.saveState()
'Move the selection box to match the current userTransform'
def selectBoxFromUser(self):
self.selectBox.blockSignals(True) self.selectBox.setState(self.selectBoxBase) self.selectBox.applyGlobalTransform(self.userTransform) self.selectBox.blockSignals(False)
'Move/scale the selection box so it fits the item\'s bounding rect. (assumes item is not rotated)'
def selectBoxToItem(self):
self.itemRect = self._graphicsItem.boundingRect() rect = self._graphicsItem.mapRectToParent(self.itemRect) self.selectBox.blockSignals(True) self.selectBox.setPos([rect.x(), rect.y()]) self.selectBox.setSize(rect.size()) self.selectBox.setAngle(0) self.selectBoxBase = self.selectBox.getState().copy() self.selectBox.blockSignals(False)
'Inform the item that its selection state has changed. **Arguments:** sel (bool) whether the item is currently selected multi (bool) whether there are multiple items currently selected'
def selectionChanged(self, sel, multi):
self.selectedAlone = (sel and (not multi)) self.showSelectBox() if self.selectedAlone: self.ctrlWidget().show() else: self.ctrlWidget().hide()
'Display the selection box around this item if it is selected and movable'
def showSelectBox(self):
if (self.selectedAlone and self.isMovable() and self.isVisible()): self.selectBox.show() else: self.selectBox.hide()
'Hide selection box while slider is moving'
def alphaPressed(self):
self.hideSelectBox()
'Set the pen used to draw border between cells. See :func:`mkPen <pyqtgraph.mkPen>` for arguments.'
def setBorder(self, *args, **kwds):
self.border = fn.mkPen(*args, **kwds) self.update()
'Advance to next row for automatic item placement'
def nextRow(self):
self.currentRow += 1 self.currentCol = (-1) self.nextColumn()
'Advance to next available column (generally only for internal use--called by addItem)'
def nextColumn(self):
self.currentCol += 1 while (self.getItem(self.currentRow, self.currentCol) is not None): self.currentCol += 1
'Alias of nextColumn'
def nextCol(self, *args, **kargs):
return self.nextColumn(*args, **kargs)
'Create a PlotItem and place it in the next available cell (or in the cell specified) All extra keyword arguments are passed to :func:`PlotItem.__init__ <pyqtgraph.PlotItem.__init__>` Returns the created item.'
def addPlot(self, row=None, col=None, rowspan=1, colspan=1, **kargs):
plot = PlotItem(**kargs) self.addItem(plot, row, col, rowspan, colspan) return plot
'Create a ViewBox and place it in the next available cell (or in the cell specified) All extra keyword arguments are passed to :func:`ViewBox.__init__ <pyqtgraph.ViewBox.__init__>` Returns the created item.'
def addViewBox(self, row=None, col=None, rowspan=1, colspan=1, **kargs):
vb = ViewBox(**kargs) self.addItem(vb, row, col, rowspan, colspan) return vb
'Create a LabelItem with *text* and place it in the next available cell (or in the cell specified) All extra keyword arguments are passed to :func:`LabelItem.__init__ <pyqtgraph.LabelItem.__init__>` Returns the created item. To create a vertical label, use *angle* = -90.'
def addLabel(self, text=' ', row=None, col=None, rowspan=1, colspan=1, **kargs):
text = LabelItem(text, **kargs) self.addItem(text, row, col, rowspan, colspan) return text
'Create an empty GraphicsLayout and place it in the next available cell (or in the cell specified) All extra keyword arguments are passed to :func:`GraphicsLayout.__init__ <pyqtgraph.GraphicsLayout.__init__>` Returns the created item.'
def addLayout(self, row=None, col=None, rowspan=1, colspan=1, **kargs):
layout = GraphicsLayout(**kargs) self.addItem(layout, row, col, rowspan, colspan) return layout
'Add an item to the layout and place it in the next available cell (or in the cell specified). The item must be an instance of a QGraphicsWidget subclass.'
def addItem(self, item, row=None, col=None, rowspan=1, colspan=1):
if (row is None): row = self.currentRow if (col is None): col = self.currentCol self.items[item] = [] for i in range(rowspan): for j in range(colspan): row2 = (row + i) col2 = (col + j) if (row2 not in self.rows): self.rows[row2] = {} self.rows[row2][col2] = item self.items[item].append((row2, col2)) self.layout.addItem(item, row, col, rowspan, colspan) self.nextColumn()
'Return the item in (*row*, *col*). If the cell is empty, return None.'
def getItem(self, row, col):
return self.rows.get(row, {}).get(col, None)
'Remove *item* from the layout.'
def removeItem(self, item):
ind = self.itemIndex(item) self.layout.removeAt(ind) self.scene().removeItem(item) for (r, c) in self.items[item]: del self.rows[r][c] del self.items[item] self.update()
'Anchors the item at its local itemPos to the item\'s parent at parentPos. Both positions are expressed in values relative to the size of the item or parent; a value of 0 indicates left or top edge, while 1 indicates right or bottom edge. Optionally, offset may be specified to introduce an absolute offset. Example: anchor a box such that its upper-right corner is fixed 10px left and 10px down from its parent\'s upper-right corner:: box.anchor(itemPos=(1,0), parentPos=(1,0), offset=(-10,10))'
def anchor(self, itemPos, parentPos, offset=(0, 0)):
parent = self.parentItem() if (parent is None): raise Exception('Cannot anchor; parent is not set.') if (self.__parent is not parent): if (self.__parent is not None): self.__parent.geometryChanged.disconnect(self.__geometryChanged) self.__parent = parent parent.geometryChanged.connect(self.__geometryChanged) self.__itemAnchor = itemPos self.__parentAnchor = parentPos self.__offset = offset self.__geometryChanged()
'Set the position of this item relative to its parent by automatically choosing appropriate anchor settings. If relative is True, one corner of the item will be anchored to the appropriate location on the parent with no offset. The anchored corner will be whichever is closest to the parent\'s boundary. If relative is False, one corner of the item will be anchored to the same corner of the parent, with an absolute offset to achieve the correct position.'
def autoAnchor(self, pos, relative=True):
pos = Point(pos) br = self.mapRectToParent(self.boundingRect()).translated((pos - self.pos())) pbr = self.parentItem().boundingRect() anchorPos = [0, 0] parentPos = Point() itemPos = Point() if (abs((br.left() - pbr.left())) < abs((br.right() - pbr.right()))): anchorPos[0] = 0 parentPos[0] = pbr.left() itemPos[0] = br.left() else: anchorPos[0] = 1 parentPos[0] = pbr.right() itemPos[0] = br.right() if (abs((br.top() - pbr.top())) < abs((br.bottom() - pbr.bottom()))): anchorPos[1] = 0 parentPos[1] = pbr.top() itemPos[1] = br.top() else: anchorPos[1] = 1 parentPos[1] = pbr.bottom() itemPos[1] = br.bottom() if relative: relPos = [((itemPos[0] - pbr.left()) / pbr.width()), ((itemPos[1] - pbr.top()) / pbr.height())] self.anchor(anchorPos, relPos) else: offset = (itemPos - parentPos) self.anchor(anchorPos, anchorPos, offset)
'**Arguments:** orientation one of \'left\', \'right\', \'top\', or \'bottom\' maxTickLength (px) maximum length of ticks to draw. Negative values draw into the plot, positive values draw outward. linkView (ViewBox) causes the range of values displayed in the axis to be linked to the visible range of a ViewBox. showValues (bool) Whether to display values adjacent to ticks pen (QPen) Pen used when drawing ticks.'
def __init__(self, orientation, pen=None, linkView=None, parent=None, maxTickLength=(-5), showValues=True):
GraphicsWidget.__init__(self, parent) self.label = QtGui.QGraphicsTextItem(self) self.picture = None self.orientation = orientation if (orientation not in ['left', 'right', 'top', 'bottom']): raise Exception("Orientation argument must be one of 'left', 'right', 'top', or 'bottom'.") if (orientation in ['left', 'right']): self.label.rotate((-90)) self.style = {'tickTextOffset': [5, 2], 'tickTextWidth': 30, 'tickTextHeight': 18, 'autoExpandTextSpace': True, 'tickFont': None, 'stopAxisAtTick': (False, False), 'textFillLimits': [(0, 0.8), (2, 0.6), (4, 0.4), (6, 0.2)], 'showValues': showValues, 'tickLength': maxTickLength, 'maxTickLevel': 2, 'maxTextLevel': 2} self.textWidth = 30 self.textHeight = 18 self.fixedWidth = None self.fixedHeight = None self.labelText = '' self.labelUnits = '' self.labelUnitPrefix = '' self.labelStyle = {} self.logMode = False self.tickFont = None self._tickLevels = None self._tickSpacing = None self.scale = 1.0 self.autoSIPrefix = True self.autoSIPrefixScale = 1.0 self.setRange(0, 1) if (pen is None): self.setPen() else: self.setPen(pen) self._linkedView = None if (linkView is not None): self.linkToView(linkView) self.showLabel(False) self.grid = False
'Set various style options. Keyword Arguments: tickLength (int) The maximum length of ticks in pixels. Positive values point toward the text; negative values point away. tickTextOffset (int) reserved spacing between text and axis in px tickTextWidth (int) Horizontal space reserved for tick text in px tickTextHeight (int) Vertical space reserved for tick text in px autoExpandTextSpace (bool) Automatically expand text space if the tick strings become too long. tickFont (QFont or None) Determines the font used for tick values. Use None for the default font. stopAxisAtTick (tuple: (bool min, bool max)) If True, the axis line is drawn only as far as the last tick. Otherwise, the line is drawn to the edge of the AxisItem boundary. textFillLimits (list of (tick #, % fill) tuples). This structure determines how the AxisItem decides how many ticks should have text appear next to them. Each tuple in the list specifies what fraction of the axis length may be occupied by text, given the number of ticks that already have text displayed. For example:: [(0, 0.8), # Never fill more than 80% of the axis (2, 0.6), # If we already have 2 ticks with text, # fill no more than 60% of the axis (4, 0.4), # If we already have 4 ticks with text, # fill no more than 40% of the axis (6, 0.2)] # If we already have 6 ticks with text, # fill no more than 20% of the axis showValues (bool) indicates whether text is displayed adjacent to ticks. Added in version 0.9.9'
def setStyle(self, **kwds):
for (kwd, value) in kwds.items(): if (kwd not in self.style): raise NameError(('%s is not a valid style argument.' % kwd)) if (kwd in ('tickLength', 'tickTextOffset', 'tickTextWidth', 'tickTextHeight')): if (not isinstance(value, int)): raise ValueError(("Argument '%s' must be int" % kwd)) if (kwd == 'tickTextOffset'): if (self.orientation in ('left', 'right')): self.style['tickTextOffset'][0] = value else: self.style['tickTextOffset'][1] = value elif (kwd == 'stopAxisAtTick'): try: assert ((len(value) == 2) and isinstance(value[0], bool) and isinstance(value[1], bool)) except: raise ValueError("Argument 'stopAxisAtTick' must have type (bool, bool)") self.style[kwd] = value else: self.style[kwd] = value self.picture = None self._adjustSize() self.update()
'Set the alpha value (0-255) for the grid, or False to disable. When grid lines are enabled, the axis tick lines are extended to cover the extent of the linked ViewBox, if any.'
def setGrid(self, grid):
self.grid = grid self.picture = None self.prepareGeometryChange() self.update()
'If *log* is True, then ticks are displayed on a logarithmic scale and values are adjusted accordingly. (This is usually accessed by changing the log mode of a :func:`PlotItem <pyqtgraph.PlotItem.setLogMode>`)'
def setLogMode(self, log):
self.logMode = log self.picture = None self.update()
'Show/hide the label text for this axis.'
def showLabel(self, show=True):
self.label.setVisible(show) if (self.orientation in ['left', 'right']): self._updateWidth() else: self._updateHeight() if self.autoSIPrefix: self.updateAutoSIPrefix()
'Set the text displayed adjacent to the axis. **Arguments:** text The text (excluding units) to display on the label for this axis. units The units for this axis. Units should generally be given without any scaling prefix (eg, \'V\' instead of \'mV\'). The scaling prefix will be automatically prepended based on the range of data displayed. **args All extra keyword arguments become CSS style options for the <span> tag which will surround the axis label and units. The final text generated for the label will look like:: <span style="...options...">{text} (prefix{units})</span> Each extra keyword argument will become a CSS option in the above template. For example, you can set the font size and color of the label:: labelStyle = {\'color\': \'#FFF\', \'font-size\': \'14pt\'} axis.setLabel(\'label text\', units=\'V\', **labelStyle)'
def setLabel(self, text=None, units=None, unitPrefix=None, **args):
if (text is not None): self.labelText = text self.showLabel() if (units is not None): self.labelUnits = units self.showLabel() if (unitPrefix is not None): self.labelUnitPrefix = unitPrefix if (len(args) > 0): self.labelStyle = args self.label.setHtml(self.labelString()) self._adjustSize() self.picture = None self.update()
'Set the height of this axis reserved for ticks and tick labels. The height of the axis label is automatically added. If *height* is None, then the value will be determined automatically based on the size of the tick text.'
def setHeight(self, h=None):
self.fixedHeight = h self._updateHeight()
'Set the width of this axis reserved for ticks and tick labels. The width of the axis label is automatically added. If *width* is None, then the value will be determined automatically based on the size of the tick text.'
def setWidth(self, w=None):
self.fixedWidth = w self._updateWidth()
'Set the pen used for drawing text, axes, ticks, and grid lines. If no arguments are given, the default foreground color will be used (see :func:`setConfigOption <pyqtgraph.setConfigOption>`).'
def setPen(self, *args, **kwargs):
self.picture = None if (args or kwargs): self._pen = fn.mkPen(*args, **kwargs) else: self._pen = fn.mkPen(getConfigOption('foreground')) self.labelStyle['color'] = ('#' + fn.colorStr(self._pen.color())[:6]) self.setLabel() self.update()
'Set the value scaling for this axis. Setting this value causes the axis to draw ticks and tick labels as if the view coordinate system were scaled. By default, the axis scaling is 1.0.'
def setScale(self, scale=None):
if (scale is None): scale = 1.0 self.enableAutoSIPrefix(True) if (scale != self.scale): self.scale = scale self.setLabel() self.picture = None self.update()
'Enable (or disable) automatic SI prefix scaling on this axis. When enabled, this feature automatically determines the best SI prefix to prepend to the label units, while ensuring that axis values are scaled accordingly. For example, if the axis spans values from -0.1 to 0.1 and has units set to \'V\' then the axis would display values -100 to 100 and the units would appear as \'mV\' This feature is enabled by default, and is only available when a suffix (unit string) is provided to display on the label.'
def enableAutoSIPrefix(self, enable=True):
self.autoSIPrefix = enable self.updateAutoSIPrefix()
'Set the range of values displayed by the axis. Usually this is handled automatically by linking the axis to a ViewBox with :func:`linkToView <pyqtgraph.AxisItem.linkToView>`'
def setRange(self, mn, mx):
if (any(np.isinf((mn, mx))) or any(np.isnan((mn, mx)))): raise Exception(('Not setting range to [%s, %s]' % (str(mn), str(mx)))) self.range = [mn, mx] if self.autoSIPrefix: self.updateAutoSIPrefix() self.picture = None self.update()
'Return the ViewBox this axis is linked to'
def linkedView(self):
if (self._linkedView is None): return None else: return self._linkedView()
'Link this axis to a ViewBox, causing its displayed range to match the visible range of the view.'
def linkToView(self, view):
oldView = self.linkedView() self._linkedView = weakref.ref(view) if (self.orientation in ['right', 'left']): if (oldView is not None): oldView.sigYRangeChanged.disconnect(self.linkedViewChanged) view.sigYRangeChanged.connect(self.linkedViewChanged) else: if (oldView is not None): oldView.sigXRangeChanged.disconnect(self.linkedViewChanged) view.sigXRangeChanged.connect(self.linkedViewChanged) if (oldView is not None): oldView.sigResized.disconnect(self.linkedViewChanged) view.sigResized.connect(self.linkedViewChanged)
'Explicitly determine which ticks to display. This overrides the behavior specified by tickSpacing(), tickValues(), and tickStrings() The format for *ticks* looks like:: [ (majorTickValue1, majorTickString1), (majorTickValue2, majorTickString2), ... ], [ (minorTickValue1, minorTickString1), (minorTickValue2, minorTickString2), ... ], If *ticks* is None, then the default tick system will be used instead.'
def setTicks(self, ticks):
self._tickLevels = ticks self.picture = None self.update()
'Explicitly determine the spacing of major and minor ticks. This overrides the default behavior of the tickSpacing method, and disables the effect of setTicks(). Arguments may be either *major* and *minor*, or *levels* which is a list of (spacing, offset) tuples for each tick level desired. If no arguments are given, then the default behavior of tickSpacing is enabled. Examples:: # two levels, all offsets = 0 axis.setTickSpacing(5, 1) # three levels, all offsets = 0 axis.setTickSpacing([(3, 0), (1, 0), (0.25, 0)]) # reset to default axis.setTickSpacing()'
def setTickSpacing(self, major=None, minor=None, levels=None):
if (levels is None): if (major is None): levels = None else: levels = [(major, 0), (minor, 0)] self._tickSpacing = levels self.picture = None self.update()
'Return values describing the desired spacing and offset of ticks. This method is called whenever the axis needs to be redrawn and is a good method to override in subclasses that require control over tick locations. The return value must be a list of tuples, one for each set of ticks:: (major tick spacing, offset), (minor tick spacing, offset), (sub-minor tick spacing, offset),'
def tickSpacing(self, minVal, maxVal, size):
if (self._tickSpacing is not None): return self._tickSpacing dif = abs((maxVal - minVal)) if (dif == 0): return [] optimalTickCount = max(2.0, np.log(size)) optimalSpacing = (dif / optimalTickCount) p10unit = (10 ** np.floor(np.log10(optimalSpacing))) intervals = (np.array([1.0, 2.0, 10.0, 20.0, 100.0]) * p10unit) minorIndex = 0 while (intervals[(minorIndex + 1)] <= optimalSpacing): minorIndex += 1 levels = [(intervals[(minorIndex + 2)], 0), (intervals[(minorIndex + 1)], 0)] if (self.style['maxTickLevel'] >= 2): minSpacing = min((size / 20.0), 30.0) maxTickCount = (size / minSpacing) if ((dif / intervals[minorIndex]) <= maxTickCount): levels.append((intervals[minorIndex], 0)) return levels
'Return the values and spacing of ticks to draw:: (spacing, [major ticks]), (spacing, [minor ticks]), By default, this method calls tickSpacing to determine the correct tick locations. This is a good method to override in subclasses.'
def tickValues(self, minVal, maxVal, size):
(minVal, maxVal) = sorted((minVal, maxVal)) minVal *= self.scale maxVal *= self.scale ticks = [] tickLevels = self.tickSpacing(minVal, maxVal, size) allValues = np.array([]) for i in range(len(tickLevels)): (spacing, offset) = tickLevels[i] start = ((np.ceil(((minVal - offset) / spacing)) * spacing) + offset) num = (int(((maxVal - start) / spacing)) + 1) values = (((np.arange(num) * spacing) + start) / self.scale) values = list(filter((lambda x: all((np.abs((allValues - x)) > (spacing * 0.01)))), values)) allValues = np.concatenate([allValues, values]) ticks.append(((spacing / self.scale), values)) if self.logMode: return self.logTickValues(minVal, maxVal, size, ticks) return ticks
'Return the strings that should be placed next to ticks. This method is called when redrawing the axis and is a good method to override in subclasses. The method is called with a list of tick values, a scaling factor (see below), and the spacing between ticks (this is required since, in some instances, there may be only one tick and thus no other way to determine the tick spacing) The scale argument is used when the axis label is displaying units which may have an SI scaling prefix. When determining the text to display, use value*scale to correctly account for this prefix. For example, if the axis label\'s units are set to \'V\', then a tick value of 0.001 might be accompanied by a scale value of 1000. This indicates that the label is displaying \'mV\', and thus the tick should display 0.001 * 1000 = 1.'
def tickStrings(self, values, scale, spacing):
if self.logMode: return self.logTickStrings(values, scale, spacing) places = max(0, np.ceil((- np.log10((spacing * scale))))) strings = [] for v in values: vs = (v * scale) if ((abs(vs) < 0.001) or (abs(vs) >= 10000)): vstr = ('%g' % vs) else: vstr = (('%%0.%df' % places) % vs) strings.append(vstr) return strings
'Calls tickValues() and tickStrings() to determine where and how ticks should be drawn, then generates from this a set of drawing commands to be interpreted by drawPicture().'
def generateDrawSpecs(self, p):
profiler = debug.Profiler() bounds = self.mapRectFromParent(self.geometry()) linkedView = self.linkedView() if ((linkedView is None) or (self.grid is False)): tickBounds = bounds else: tickBounds = linkedView.mapRectToItem(self, linkedView.boundingRect()) if (self.orientation == 'left'): span = (bounds.topRight(), bounds.bottomRight()) tickStart = tickBounds.right() tickStop = bounds.right() tickDir = (-1) axis = 0 elif (self.orientation == 'right'): span = (bounds.topLeft(), bounds.bottomLeft()) tickStart = tickBounds.left() tickStop = bounds.left() tickDir = 1 axis = 0 elif (self.orientation == 'top'): span = (bounds.bottomLeft(), bounds.bottomRight()) tickStart = tickBounds.bottom() tickStop = bounds.bottom() tickDir = (-1) axis = 1 elif (self.orientation == 'bottom'): span = (bounds.topLeft(), bounds.topRight()) tickStart = tickBounds.top() tickStop = bounds.top() tickDir = 1 axis = 1 points = list(map(self.mapToDevice, span)) if (None in points): return lengthInPixels = Point((points[1] - points[0])).length() if (lengthInPixels == 0): return if (self._tickLevels is None): tickLevels = self.tickValues(self.range[0], self.range[1], lengthInPixels) tickStrings = None else: tickLevels = [] tickStrings = [] for level in self._tickLevels: values = [] strings = [] tickLevels.append((None, values)) tickStrings.append(strings) for (val, strn) in level: values.append(val) strings.append(strn) dif = (self.range[1] - self.range[0]) if (dif == 0): xScale = 1 offset = 0 elif (axis == 0): xScale = ((- bounds.height()) / dif) offset = ((self.range[0] * xScale) - bounds.height()) else: xScale = (bounds.width() / dif) offset = (self.range[0] * xScale) xRange = [((x * xScale) - offset) for x in self.range] xMin = min(xRange) xMax = max(xRange) profiler('init') tickPositions = [] tickSpecs = [] for i in range(len(tickLevels)): tickPositions.append([]) ticks = tickLevels[i][1] tickLength = (self.style['tickLength'] / ((i * 0.5) + 1.0)) lineAlpha = (255 / (i + 1)) if (self.grid is not False): lineAlpha *= ((self.grid / 255.0) * np.clip(((0.05 * lengthInPixels) / (len(ticks) + 1)), 0.0, 1.0)) for v in ticks: x = ((v * xScale) - offset) if ((x < xMin) or (x > xMax)): tickPositions[i].append(None) continue tickPositions[i].append(x) p1 = [x, x] p2 = [x, x] p1[axis] = tickStart p2[axis] = tickStop if (self.grid is False): p2[axis] += (tickLength * tickDir) tickPen = self.pen() color = tickPen.color() color.setAlpha(lineAlpha) tickPen.setColor(color) tickSpecs.append((tickPen, Point(p1), Point(p2))) profiler('compute ticks') if (self.style['stopAxisAtTick'][0] is True): stop = max(span[0].y(), min(map(min, tickPositions))) if (axis == 0): span[0].setY(stop) else: span[0].setX(stop) if (self.style['stopAxisAtTick'][1] is True): stop = min(span[1].y(), max(map(max, tickPositions))) if (axis == 0): span[1].setY(stop) else: span[1].setX(stop) axisSpec = (self.pen(), span[0], span[1]) textOffset = self.style['tickTextOffset'][axis] textSize2 = 0 textRects = [] textSpecs = [] if (not self.style['showValues']): return (axisSpec, tickSpecs, textSpecs) for i in range(min(len(tickLevels), (self.style['maxTextLevel'] + 1))): if (tickStrings is None): (spacing, values) = tickLevels[i] strings = self.tickStrings(values, (self.autoSIPrefixScale * self.scale), spacing) else: strings = tickStrings[i] if (len(strings) == 0): continue for j in range(len(strings)): if (tickPositions[i][j] is None): strings[j] = None rects = [] for s in strings: if (s is None): rects.append(None) else: br = p.boundingRect(QtCore.QRectF(0, 0, 100, 100), QtCore.Qt.AlignCenter, asUnicode(s)) br.setHeight((br.height() * 0.8)) rects.append(br) textRects.append(rects[(-1)]) if (len(textRects) > 0): if (axis == 0): textSize = np.sum([r.height() for r in textRects]) textSize2 = np.max([r.width() for r in textRects]) else: textSize = np.sum([r.width() for r in textRects]) textSize2 = np.max([r.height() for r in textRects]) else: textSize = 0 textSize2 = 0 if (i > 0): textFillRatio = (float(textSize) / lengthInPixels) finished = False for (nTexts, limit) in self.style['textFillLimits']: if ((len(textSpecs) >= nTexts) and (textFillRatio >= limit)): finished = True break if finished: break for j in range(len(strings)): vstr = strings[j] if (vstr is None): continue vstr = asUnicode(vstr) x = tickPositions[i][j] textRect = rects[j] height = textRect.height() width = textRect.width() offset = (max(0, self.style['tickLength']) + textOffset) if (self.orientation == 'left'): textFlags = ((QtCore.Qt.TextDontClip | QtCore.Qt.AlignRight) | QtCore.Qt.AlignVCenter) rect = QtCore.QRectF(((tickStop - offset) - width), (x - (height / 2)), width, height) elif (self.orientation == 'right'): textFlags = ((QtCore.Qt.TextDontClip | QtCore.Qt.AlignLeft) | QtCore.Qt.AlignVCenter) rect = QtCore.QRectF((tickStop + offset), (x - (height / 2)), width, height) elif (self.orientation == 'top'): textFlags = ((QtCore.Qt.TextDontClip | QtCore.Qt.AlignCenter) | QtCore.Qt.AlignBottom) rect = QtCore.QRectF((x - (width / 2.0)), ((tickStop - offset) - height), width, height) elif (self.orientation == 'bottom'): textFlags = ((QtCore.Qt.TextDontClip | QtCore.Qt.AlignCenter) | QtCore.Qt.AlignTop) rect = QtCore.QRectF((x - (width / 2.0)), (tickStop + offset), width, height) textSpecs.append((rect, textFlags, vstr)) profiler('compute text') self._updateMaxTextSize(textSize2) return (axisSpec, tickSpecs, textSpecs)
'Position can be set either as an index referring to the sample number or the position 0.0 - 1.0 If *rotate* is True, then the item rotates to match the tangent of the curve.'
def __init__(self, curve, index=0, pos=None, rotate=True):
GraphicsObject.__init__(self) self._rotate = rotate self.curve = weakref.ref(curve) self.setParentItem(curve) self.setProperty('position', 0.0) self.setProperty('index', 0) if hasattr(self, 'ItemHasNoContents'): self.setFlags((self.flags() | self.ItemHasNoContents)) if (pos is not None): self.setPos(pos) else: self.setIndex(index)
'Arrows can be initialized with any keyword arguments accepted by the setStyle() method.'
def __init__(self, **opts):
self.opts = {} QtGui.QGraphicsPathItem.__init__(self, opts.get('parent', None)) if ('size' in opts): opts['headLen'] = opts['size'] if ('width' in opts): opts['headWidth'] = opts['width'] defaultOpts = {'pxMode': True, 'angle': (-150), 'pos': (0, 0), 'headLen': 20, 'tipAngle': 25, 'baseAngle': 0, 'tailLen': None, 'tailWidth': 3, 'pen': (200, 200, 200), 'brush': (50, 50, 200)} defaultOpts.update(opts) self.setStyle(**defaultOpts) self.rotate(self.opts['angle']) self.moveBy(*self.opts['pos'])
'Changes the appearance of the arrow. All arguments are optional: **Keyword Arguments:** angle Orientation of the arrow in degrees. Default is 0; arrow pointing to the left. headLen Length of the arrow head, from tip to base. default=20 headWidth Width of the arrow head at its base. tipAngle Angle of the tip of the arrow in degrees. Smaller values make a \'sharper\' arrow. If tipAngle is specified, ot overrides headWidth. default=25 baseAngle Angle of the base of the arrow head. Default is 0, which means that the base of the arrow head is perpendicular to the arrow tail. tailLen Length of the arrow tail, measured from the base of the arrow head to the end of the tail. If this value is None, no tail will be drawn. default=None tailWidth Width of the tail. default=3 pen The pen used to draw the outline of the arrow. brush The brush used to fill the arrow.'
def setStyle(self, **opts):
self.opts.update(opts) opt = dict([(k, self.opts[k]) for k in ['headLen', 'tipAngle', 'baseAngle', 'tailLen', 'tailWidth']]) self.path = fn.makeArrowPath(**opt) self.setPath(self.path) self.setPen(fn.mkPen(self.opts['pen'])) self.setBrush(fn.mkBrush(self.opts['brush'])) if self.opts['pxMode']: self.setFlags((self.flags() | self.ItemIgnoresTransformations)) else: self.setFlags((self.flags() & (~ self.ItemIgnoresTransformations)))
'Create a new PlotItem. All arguments are optional. Any extra keyword arguments are passed to PlotItem.plot(). **Arguments:** *title* Title to display at the top of the item. Html is allowed. *labels* A dictionary specifying the axis labels to display:: {\'left\': (args), \'bottom\': (args), ...} The name of each axis and the corresponding arguments are passed to :func:`PlotItem.setLabel() <pyqtgraph.PlotItem.setLabel>` Optionally, PlotItem my also be initialized with the keyword arguments left, right, top, or bottom to achieve the same effect. *name* Registers a name for this view so that others may link to it *viewBox* If specified, the PlotItem will be constructed with this as its ViewBox. *axisItems* Optional dictionary instructing the PlotItem to use pre-constructed items for its axes. The dict keys must be axis names (\'left\', \'bottom\', \'right\', \'top\') and the values must be instances of AxisItem (or at least compatible with AxisItem).'
def __init__(self, parent=None, name=None, labels=None, title=None, viewBox=None, axisItems=None, enableMenu=True, **kargs):
GraphicsWidget.__init__(self, parent) self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) path = os.path.dirname(__file__) self.autoBtn = ButtonItem(pixmaps.getPixmap('auto'), 14, self) self.autoBtn.mode = 'auto' self.autoBtn.clicked.connect(self.autoBtnClicked) self.buttonsHidden = False self.mouseHovering = False self.layout = QtGui.QGraphicsGridLayout() self.layout.setContentsMargins(1, 1, 1, 1) self.setLayout(self.layout) self.layout.setHorizontalSpacing(0) self.layout.setVerticalSpacing(0) if (viewBox is None): viewBox = ViewBox(parent=self) self.vb = viewBox self.vb.sigStateChanged.connect(self.viewStateChanged) self.setMenuEnabled(enableMenu, enableMenu) if (name is not None): self.vb.register(name) self.vb.sigRangeChanged.connect(self.sigRangeChanged) self.vb.sigXRangeChanged.connect(self.sigXRangeChanged) self.vb.sigYRangeChanged.connect(self.sigYRangeChanged) self.layout.addItem(self.vb, 2, 1) self.alpha = 1.0 self.autoAlpha = True self.spectrumMode = False self.legend = None if (axisItems is None): axisItems = {} self.axes = {} for (k, pos) in (('top', (1, 1)), ('bottom', (3, 1)), ('left', (2, 0)), ('right', (2, 2))): if (k in axisItems): axis = axisItems[k] else: axis = AxisItem(orientation=k, parent=self) axis.linkToView(self.vb) self.axes[k] = {'item': axis, 'pos': pos} self.layout.addItem(axis, *pos) axis.setZValue((-1000)) axis.setFlag(axis.ItemNegativeZStacksBehindParent) self.titleLabel = LabelItem('', size='11pt', parent=self) self.layout.addItem(self.titleLabel, 0, 1) self.setTitle(None) for i in range(4): self.layout.setRowPreferredHeight(i, 0) self.layout.setRowMinimumHeight(i, 0) self.layout.setRowSpacing(i, 0) self.layout.setRowStretchFactor(i, 1) for i in range(3): self.layout.setColumnPreferredWidth(i, 0) self.layout.setColumnMinimumWidth(i, 0) self.layout.setColumnSpacing(i, 0) self.layout.setColumnStretchFactor(i, 1) self.layout.setRowStretchFactor(2, 100) self.layout.setColumnStretchFactor(1, 100) self.items = [] self.curves = [] self.itemMeta = weakref.WeakKeyDictionary() self.dataItems = [] self.paramList = {} self.avgCurves = {} w = QtGui.QWidget() self.ctrl = c = Ui_Form() c.setupUi(w) dv = QtGui.QDoubleValidator(self) menuItems = [('Transforms', c.transformGroup), ('Downsample', c.decimateGroup), ('Average', c.averageGroup), ('Alpha', c.alphaGroup), ('Grid', c.gridGroup), ('Points', c.pointsGroup)] self.ctrlMenu = QtGui.QMenu() self.ctrlMenu.setTitle('Plot Options') self.subMenus = [] for (name, grp) in menuItems: sm = QtGui.QMenu(name) act = QtGui.QWidgetAction(self) act.setDefaultWidget(grp) sm.addAction(act) self.subMenus.append(sm) self.ctrlMenu.addMenu(sm) self.stateGroup = WidgetGroup() for (name, w) in menuItems: self.stateGroup.autoAdd(w) self.fileDialog = None c.alphaGroup.toggled.connect(self.updateAlpha) c.alphaSlider.valueChanged.connect(self.updateAlpha) c.autoAlphaCheck.toggled.connect(self.updateAlpha) c.xGridCheck.toggled.connect(self.updateGrid) c.yGridCheck.toggled.connect(self.updateGrid) c.gridAlphaSlider.valueChanged.connect(self.updateGrid) c.fftCheck.toggled.connect(self.updateSpectrumMode) c.logXCheck.toggled.connect(self.updateLogMode) c.logYCheck.toggled.connect(self.updateLogMode) c.downsampleSpin.valueChanged.connect(self.updateDownsampling) c.downsampleCheck.toggled.connect(self.updateDownsampling) c.autoDownsampleCheck.toggled.connect(self.updateDownsampling) c.subsampleRadio.toggled.connect(self.updateDownsampling) c.meanRadio.toggled.connect(self.updateDownsampling) c.clipToViewCheck.toggled.connect(self.updateDownsampling) self.ctrl.avgParamList.itemClicked.connect(self.avgParamListClicked) self.ctrl.averageGroup.toggled.connect(self.avgToggled) self.ctrl.maxTracesCheck.toggled.connect(self.updateDecimation) self.ctrl.maxTracesSpin.valueChanged.connect(self.updateDecimation) self.hideAxis('right') self.hideAxis('top') self.showAxis('left') self.showAxis('bottom') if (labels is None): labels = {} for label in list(self.axes.keys()): if (label in kargs): labels[label] = kargs[label] del kargs[label] for k in labels: if isinstance(labels[k], basestring): labels[k] = (labels[k],) self.setLabel(k, *labels[k]) if (title is not None): self.setTitle(title) if (len(kargs) > 0): self.plot(**kargs)
'Return the :class:`ViewBox <pyqtgraph.ViewBox>` contained within.'
def getViewBox(self):
return self.vb
'Set log scaling for x and/or y axes. This informs PlotDataItems to transform logarithmically and switches the axes to use log ticking. Note that *no other items* in the scene will be affected by this; there is (currently) no generic way to redisplay a GraphicsItem with log coordinates.'
def setLogMode(self, x=None, y=None):
if (x is not None): self.ctrl.logXCheck.setChecked(x) if (y is not None): self.ctrl.logYCheck.setChecked(y)
'Show or hide the grid for either axis. **Arguments:** x (bool) Whether to show the X grid y (bool) Whether to show the Y grid alpha (0.0-1.0) Opacity of the grid'
def showGrid(self, x=None, y=None, alpha=None):
if ((x is None) and (y is None) and (alpha is None)): raise Exception('Must specify at least one of x, y, or alpha.') if (x is not None): self.ctrl.xGridCheck.setChecked(x) if (y is not None): self.ctrl.yGridCheck.setChecked(y) if (alpha is not None): v = (np.clip(alpha, 0, 1) * self.ctrl.gridAlphaSlider.maximum()) self.ctrl.gridAlphaSlider.setValue(v)
'Return the screen geometry of the viewbox'
def viewGeometry(self):
v = self.scene().views()[0] b = self.vb.mapRectToScene(self.vb.boundingRect()) wr = v.mapFromScene(b).boundingRect() pos = v.mapToGlobal(v.pos()) wr.adjust(pos.x(), pos.y(), pos.x(), pos.y()) return wr
'Enable auto-scaling. The plot will continuously scale to fit the boundaries of its data.'
def enableAutoScale(self):
print 'Warning: enableAutoScale is deprecated. Use enableAutoRange(axis, enable) instead.' self.vb.enableAutoRange(self.vb.XYAxes)
'Add a graphics item to the view box. If the item has plot data (PlotDataItem, PlotCurveItem, ScatterPlotItem), it may be included in analysis performed by the PlotItem.'
def addItem(self, item, *args, **kargs):
self.items.append(item) vbargs = {} if ('ignoreBounds' in kargs): vbargs['ignoreBounds'] = kargs['ignoreBounds'] self.vb.addItem(item, *args, **vbargs) name = None if (hasattr(item, 'implements') and item.implements('plotData')): name = item.name() self.dataItems.append(item) params = kargs.get('params', {}) self.itemMeta[item] = params self.curves.append(item) if hasattr(item, 'setLogMode'): item.setLogMode(self.ctrl.logXCheck.isChecked(), self.ctrl.logYCheck.isChecked()) if isinstance(item, PlotDataItem): (alpha, auto) = self.alphaState() item.setAlpha(alpha, auto) item.setFftMode(self.ctrl.fftCheck.isChecked()) item.setDownsampling(*self.downsampleMode()) item.setClipToView(self.clipToViewMode()) item.setPointMode(self.pointMode()) self.updateDecimation() self.updateParamList() if (self.ctrl.averageGroup.isChecked() and ('skipAverage' not in kargs)): self.addAvgCurve(item) if ((name is not None) and hasattr(self, 'legend') and (self.legend is not None)): self.legend.addItem(item, name=name)
'Return a list of all data items (PlotDataItem, PlotCurveItem, ScatterPlotItem, etc) contained in this PlotItem.'
def listDataItems(self):
return self.dataItems[:]
'Create an InfiniteLine and add to the plot. If *x* is specified, the line will be vertical. If *y* is specified, the line will be horizontal. All extra keyword arguments are passed to :func:`InfiniteLine.__init__() <pyqtgraph.InfiniteLine.__init__>`. Returns the item created.'
def addLine(self, x=None, y=None, z=None, **kwds):
pos = kwds.get('pos', (x if (x is not None) else y)) angle = kwds.get('angle', (0 if (x is None) else 90)) line = InfiniteLine(pos, angle, **kwds) self.addItem(line) if (z is not None): line.setZValue(z) return line