desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'By default, the positive x-axis points rightward on the screen. Use invertX(True) to reverse the x-axis.'
| def invertX(self, b=True):
| self._invertAxis(0, b)
|
'If the aspect ratio is locked, view scaling must always preserve the aspect ratio.
By default, the ratio is set to 1; x and y both have the same scaling.
This ratio can be overridden (xScale/yScale), or use None to lock in the current ratio.'
| def setAspectLocked(self, lock=True, ratio=1):
| if (not lock):
if (self.state['aspectLocked'] == False):
return
self.state['aspectLocked'] = False
else:
rect = self.rect()
vr = self.viewRect()
if ((rect.height() == 0) or (vr.width() == 0) or (vr.height() == 0)):
currentRatio = 1.0
else:
currentRatio = ((rect.width() / float(rect.height())) / (vr.width() / vr.height()))
if (ratio is None):
ratio = currentRatio
if (self.state['aspectLocked'] == ratio):
return
self.state['aspectLocked'] = ratio
if (ratio != currentRatio):
self.updateViewRange()
self.updateAutoRange()
self.updateViewRange()
self.sigStateChanged.emit(self)
|
'Return the transform that maps from child(item in the childGroup) coordinates to local coordinates.
(This maps from inside the viewbox to outside)'
| def childTransform(self):
| self.updateMatrix()
m = self.childGroup.transform()
return m
|
'Maps from the local coordinates of the ViewBox to the coordinate system displayed inside the ViewBox'
| def mapToView(self, obj):
| m = fn.invertQTransform(self.childTransform())
return m.map(obj)
|
'Maps from the coordinate system displayed inside the ViewBox to the local coordinates of the ViewBox'
| def mapFromView(self, obj):
| m = self.childTransform()
return m.map(obj)
|
'Maps from scene coordinates to the coordinate system displayed inside the ViewBox'
| def mapSceneToView(self, obj):
| return self.mapToView(self.mapFromScene(obj))
|
'Maps from the coordinate system displayed inside the ViewBox to scene coordinates'
| def mapViewToScene(self, obj):
| return self.mapToScene(self.mapFromView(obj))
|
'Maps *obj* from the local coordinate system of *item* to the view coordinates'
| def mapFromItemToView(self, item, obj):
| return self.childGroup.mapFromItem(item, obj)
|
'Maps *obj* from view coordinates to the local coordinate system of *item*.'
| def mapFromViewToItem(self, item, obj):
| return self.childGroup.mapToItem(item, obj)
|
'Return the (width, height) of a screen pixel in view coordinates.'
| def viewPixelSize(self):
| o = self.mapToView(Point(0, 0))
(px, py) = [Point((self.mapToView(v) - o)) for v in self.pixelVectors()]
return (px.length(), py.length())
|
'Return the bounding rect of the item in view coordinates'
| def itemBoundingRect(self, item):
| return self.mapSceneToView(item.sceneBoundingRect()).boundingRect()
|
'This routine should capture key presses in the current view box.
Key presses are used only when mouse mode is RectMode
The following events are implemented:
ctrl-A : zooms out to the default "full" view of the plot
ctrl-+ : moves forward in the zooming stack (if it exists)
ctrl-- : moves backward in the zooming stack (if it exists)'
| def keyPressEvent(self, ev):
| ev.accept()
if (ev.text() == '-'):
self.scaleHistory((-1))
elif (ev.text() in ['+', '=']):
self.scaleHistory(1)
elif (ev.key() == QtCore.Qt.Key_Backspace):
self.scaleHistory(len(self.axHistory))
else:
ev.ignore()
|
'Return a list of all children and grandchildren of this ViewBox'
| def allChildren(self, item=None):
| if (item is None):
item = self.childGroup
children = [item]
for ch in item.childItems():
children.extend(self.allChildren(ch))
return children
|
'Return the bounding range of all children.
[[xmin, xmax], [ymin, ymax]]
Values may be None if there are no specific bounds for an axis.'
| def childrenBounds(self, frac=None, orthoRange=(None, None), items=None):
| profiler = debug.Profiler()
if (items is None):
items = self.addedItems
(px, py) = [(v.length() if (v is not None) else 0) for v in self.childGroup.pixelVectors()]
itemBounds = []
for item in items:
if (not item.isVisible()):
continue
useX = True
useY = True
if hasattr(item, 'dataBounds'):
if (frac is None):
frac = (1.0, 1.0)
xr = item.dataBounds(0, frac=frac[0], orthoRange=orthoRange[0])
yr = item.dataBounds(1, frac=frac[1], orthoRange=orthoRange[1])
pxPad = (0 if (not hasattr(item, 'pixelPadding')) else item.pixelPadding())
if ((xr is None) or ((xr[0] is None) and (xr[1] is None)) or np.isnan(xr).any() or np.isinf(xr).any()):
useX = False
xr = (0, 0)
if ((yr is None) or ((yr[0] is None) and (yr[1] is None)) or np.isnan(yr).any() or np.isinf(yr).any()):
useY = False
yr = (0, 0)
bounds = QtCore.QRectF(xr[0], yr[0], (xr[1] - xr[0]), (yr[1] - yr[0]))
bounds = self.mapFromItemToView(item, bounds).boundingRect()
if (not any([useX, useY])):
continue
if (useX != useY):
ang = round(item.transformAngle())
if ((ang == 0) or (ang == 180)):
pass
elif ((ang == 90) or (ang == 270)):
(useX, useY) = (useY, useX)
else:
continue
itemBounds.append((bounds, useX, useY, pxPad))
else:
if (int((item.flags() & item.ItemHasNoContents)) > 0):
continue
else:
bounds = item.boundingRect()
bounds = self.mapFromItemToView(item, bounds).boundingRect()
itemBounds.append((bounds, True, True, 0))
range = [None, None]
for (bounds, useX, useY, px) in itemBounds:
if useY:
if (range[1] is not None):
range[1] = [min(bounds.top(), range[1][0]), max(bounds.bottom(), range[1][1])]
else:
range[1] = [bounds.top(), bounds.bottom()]
if useX:
if (range[0] is not None):
range[0] = [min(bounds.left(), range[0][0]), max(bounds.right(), range[0][1])]
else:
range[0] = [bounds.left(), bounds.right()]
profiler()
w = self.width()
h = self.height()
if ((w > 0) and (range[0] is not None)):
pxSize = ((range[0][1] - range[0][0]) / w)
for (bounds, useX, useY, px) in itemBounds:
if ((px == 0) or (not useX)):
continue
range[0][0] = min(range[0][0], (bounds.left() - (px * pxSize)))
range[0][1] = max(range[0][1], (bounds.right() + (px * pxSize)))
if ((h > 0) and (range[1] is not None)):
pxSize = ((range[1][1] - range[1][0]) / h)
for (bounds, useX, useY, px) in itemBounds:
if ((px == 0) or (not useY)):
continue
range[1][0] = min(range[1][0], (bounds.top() - (px * pxSize)))
range[1][1] = max(range[1][1], (bounds.bottom() + (px * pxSize)))
return range
|
'Temporarily display the bounding rect of an item and lines connecting to the center of the view.
This is useful for determining the location of items that may be out of the range of the ViewBox.
if allChildren is True, then the bounding rect of all item\'s children will be shown instead.'
| def locate(self, item, timeout=3.0, children=False):
| self.clearLocate()
if (item.scene() is not self.scene()):
raise Exception('Item does not share a scene with this ViewBox.')
c = self.viewRect().center()
if children:
br = self.mapFromItemToView(item, item.childrenBoundingRect()).boundingRect()
else:
br = self.mapFromItemToView(item, item.boundingRect()).boundingRect()
g = ItemGroup()
g.setParentItem(self.childGroup)
self.locateGroup = g
g.box = QtGui.QGraphicsRectItem(br)
g.box.setParentItem(g)
g.lines = []
for p in (br.topLeft(), br.bottomLeft(), br.bottomRight(), br.topRight()):
line = QtGui.QGraphicsLineItem(c.x(), c.y(), p.x(), p.y())
line.setParentItem(g)
g.lines.append(line)
for item in g.childItems():
item.setPen(fn.mkPen(color='y', width=3))
g.setZValue(1000000)
if children:
g.path = QtGui.QGraphicsPathItem(g.childrenShape())
else:
g.path = QtGui.QGraphicsPathItem(g.shape())
g.path.setParentItem(g)
g.path.setPen(fn.mkPen('g'))
g.path.setZValue(100)
QtCore.QTimer.singleShot((timeout * 1000), self.clearLocate)
|
'**Arguments:**
*text* The text to display
*color* The color of the text (any format accepted by pg.mkColor)
*html* If specified, this overrides both *text* and *color*
*anchor* A QPointF or (x,y) sequence indicating what region of the text box will
be anchored to the item\'s position. A value of (0,0) sets the upper-left corner
of the text box to be at the position specified by setPos(), while a value of (1,1)
sets the lower-right corner.
*border* A pen to use when drawing the border
*fill* A brush to use when filling within the border
*angle* Angle in degrees to rotate text. Default is 0; text will be displayed upright.
*rotateAxis* If None, then a text angle of 0 always points along the +x axis of the scene.
If a QPointF or (x,y) sequence is given, then it represents a vector direction
in the parent\'s coordinate system that the 0-degree line will be aligned to. This
Allows text to follow both the position and orientation of its parent while still
discarding any scale and shear factors.
The effects of the `rotateAxis` and `angle` arguments are added independently. So for example:
* rotateAxis=None, angle=0 -> normal horizontal text
* rotateAxis=None, angle=90 -> normal vertical text
* rotateAxis=(1, 0), angle=0 -> text aligned with x axis of its parent
* rotateAxis=(0, 1), angle=0 -> text aligned with y axis of its parent
* rotateAxis=(1, 0), angle=90 -> text orthogonal to x axis of its parent'
| def __init__(self, text='', color=(200, 200, 200), html=None, anchor=(0, 0), border=None, fill=None, angle=0, rotateAxis=None):
| self.anchor = Point(anchor)
self.rotateAxis = (None if (rotateAxis is None) else Point(rotateAxis))
GraphicsObject.__init__(self)
self.textItem = QtGui.QGraphicsTextItem()
self.textItem.setParentItem(self)
self._lastTransform = None
self._lastScene = None
self._bounds = QtCore.QRectF()
if (html is None):
self.setColor(color)
self.setText(text)
else:
self.setHtml(html)
self.fill = fn.mkBrush(fill)
self.border = fn.mkPen(border)
self.setAngle(angle)
|
'Set the text of this item.
This method sets the plain text of the item; see also setHtml().'
| def setText(self, text, color=None):
| if (color is not None):
self.setColor(color)
self.textItem.setPlainText(text)
self.updateTextPos()
|
'Set the plain text to be rendered by this item.
See QtGui.QGraphicsTextItem.setPlainText().'
| def setPlainText(self, *args):
| self.textItem.setPlainText(*args)
self.updateTextPos()
|
'Set the HTML code to be rendered by this item.
See QtGui.QGraphicsTextItem.setHtml().'
| def setHtml(self, *args):
| self.textItem.setHtml(*args)
self.updateTextPos()
|
'Set the width of the text.
If the text requires more space than the width limit, then it will be
wrapped into multiple lines.
See QtGui.QGraphicsTextItem.setTextWidth().'
| def setTextWidth(self, *args):
| self.textItem.setTextWidth(*args)
self.updateTextPos()
|
'Set the font for this text.
See QtGui.QGraphicsTextItem.setFont().'
| def setFont(self, *args):
| self.textItem.setFont(*args)
self.updateTextPos()
|
'Set the color for this text.
See QtGui.QGraphicsItem.setDefaultTextColor().'
| def setColor(self, color):
| self.color = fn.mkColor(color)
self.textItem.setDefaultTextColor(self.color)
|
'If *image* (ImageItem) is provided, then the control will be automatically linked to the image and changes to the control will be immediately reflected in the image\'s appearance.
By default, the histogram is rendered with a fill. For performance, set *fillHistogram* = False.'
| def __init__(self, image=None, fillHistogram=True):
| GraphicsWidget.__init__(self)
self.lut = None
self.imageItem = (lambda : None)
self.layout = QtGui.QGraphicsGridLayout()
self.setLayout(self.layout)
self.layout.setContentsMargins(1, 1, 1, 1)
self.layout.setSpacing(0)
self.vb = ViewBox(parent=self)
self.vb.setMaximumWidth(152)
self.vb.setMinimumWidth(45)
self.vb.setMouseEnabled(x=False, y=True)
self.gradient = GradientEditorItem()
self.gradient.setOrientation('right')
self.gradient.loadPreset('grey')
self.region = LinearRegionItem([0, 1], LinearRegionItem.Horizontal)
self.region.setZValue(1000)
self.vb.addItem(self.region)
self.axis = AxisItem('left', linkView=self.vb, maxTickLength=(-10), parent=self)
self.layout.addItem(self.axis, 0, 0)
self.layout.addItem(self.vb, 0, 1)
self.layout.addItem(self.gradient, 0, 2)
self.range = None
self.gradient.setFlag(self.gradient.ItemStacksBehindParent)
self.vb.setFlag(self.gradient.ItemStacksBehindParent)
self.gradient.sigGradientChanged.connect(self.gradientChanged)
self.region.sigRegionChanged.connect(self.regionChanging)
self.region.sigRegionChangeFinished.connect(self.regionChanged)
self.vb.sigRangeChanged.connect(self.viewRangeChanged)
self.plot = PlotDataItem()
self.plot.rotate(90)
self.fillHistogram(fillHistogram)
self.vb.addItem(self.plot)
self.autoHistogramRange()
if (image is not None):
self.setImageItem(image)
|
'Set the Y range on the histogram plot. This disables auto-scaling.'
| def setHistogramRange(self, mn, mx, padding=0.1):
| self.vb.enableAutoRange(self.vb.YAxis, False)
self.vb.setYRange(mn, mx, padding)
|
'Enable auto-scaling on the histogram plot.'
| def autoHistogramRange(self):
| self.vb.enableAutoRange(self.vb.XYAxes)
|
'Set an ImageItem to have its levels and LUT automatically controlled
by this HistogramLUTItem.'
| def setImageItem(self, img):
| self.imageItem = weakref.ref(img)
img.sigImageChanged.connect(self.imageChanged)
img.setLookupTable(self.getLookupTable)
self.regionChanged()
self.imageChanged(autoLevel=True)
|
'Return a lookup table from the color gradient defined by this
HistogramLUTItem.'
| def getLookupTable(self, img=None, n=None, alpha=None):
| if (n is None):
if (img.dtype == np.uint8):
n = 256
else:
n = 512
if (self.lut is None):
self.lut = self.gradient.getLookupTable(n, alpha=alpha)
return self.lut
|
'Return the min and max levels.'
| def getLevels(self):
| return self.region.getRegion()
|
'Set the min and max levels.'
| def setLevels(self, mn, mx):
| self.region.setRegion([mn, mx])
|
'Return the state of the widget in a format suitable for storing to
disk. (Points are converted to tuple)
Combined with setState(), this allows ROIs to be easily saved and
restored.'
| def saveState(self):
| state = {}
state['pos'] = tuple(self.state['pos'])
state['size'] = tuple(self.state['size'])
state['angle'] = self.state['angle']
return state
|
'Set the state of the ROI from a structure generated by saveState() or
getState().'
| def setState(self, state, update=True):
| self.setPos(state['pos'], update=False)
self.setSize(state['size'], update=False)
self.setAngle(state['angle'], update=update)
|
'Return the bounding rectangle of this ROI in the coordinate system
of its parent.'
| def parentBounds(self):
| return self.mapToParent(self.boundingRect()).boundingRect()
|
'Set the pen to use when drawing the ROI shape.
For arguments, see :func:`mkPen <pyqtgraph.mkPen>`.'
| def setPen(self, *args, **kwargs):
| self.pen = fn.mkPen(*args, **kwargs)
self.currentPen = self.pen
self.update()
|
'Return the size (w,h) of the ROI.'
| def size(self):
| return self.getState()['size']
|
'Return the position (x,y) of the ROI\'s origin.
For most ROIs, this will be the lower-left corner.'
| def pos(self):
| return self.getState()['pos']
|
'Return the angle of the ROI in degrees.'
| def angle(self):
| return self.getState()['angle']
|
'Set the position of the ROI (in the parent\'s coordinate system).
Accepts either separate (x, y) arguments or a single :class:`Point` or
``QPointF`` argument.
By default, this method causes both ``sigRegionChanged`` and
``sigRegionChangeFinished`` to be emitted. If *finish* is False, then
``sigRegionChangeFinished`` will not be emitted. You can then use
stateChangeFinished() to cause the signal to be emitted after a series
of state changes.
If *update* is False, the state change will be remembered but not processed and no signals
will be emitted. You can then use stateChanged() to complete the state change. This allows
multiple change functions to be called sequentially while minimizing processing overhead
and repeated signals. Setting ``update=False`` also forces ``finish=False``.'
| def setPos(self, pos, y=None, update=True, finish=True):
| if (y is None):
pos = Point(pos)
else:
if isinstance(y, bool):
raise TypeError('Positional arguments to setPos() must be numerical.')
pos = Point(pos, y)
self.state['pos'] = pos
QtGui.QGraphicsItem.setPos(self, pos)
if update:
self.stateChanged(finish=finish)
|
'Set the size of the ROI. May be specified as a QPoint, Point, or list of two values.
See setPos() for an explanation of the update and finish arguments.'
| def setSize(self, size, update=True, finish=True):
| size = Point(size)
self.prepareGeometryChange()
self.state['size'] = size
if update:
self.stateChanged(finish=finish)
|
'Set the angle of rotation (in degrees) for this ROI.
See setPos() for an explanation of the update and finish arguments.'
| def setAngle(self, angle, update=True, finish=True):
| self.state['angle'] = angle
tr = QtGui.QTransform()
tr.rotate(angle)
self.setTransform(tr)
if update:
self.stateChanged(finish=finish)
|
'Resize the ROI by scaling relative to *center*.
See setPos() for an explanation of the *update* and *finish* arguments.'
| def scale(self, s, center=[0, 0], update=True, finish=True):
| c = self.mapToParent((Point(center) * self.state['size']))
self.prepareGeometryChange()
newSize = (self.state['size'] * s)
c1 = self.mapToParent((Point(center) * newSize))
newPos = ((self.state['pos'] + c) - c1)
self.setSize(newSize, update=False)
self.setPos(newPos, update=update, finish=finish)
|
'Move the ROI to a new position.
Accepts either (x, y, snap) or ([x,y], snap) as arguments
If the ROI is bounded and the move would exceed boundaries, then the ROI
is moved to the nearest acceptable position instead.
*snap* can be:
None (default) use self.translateSnap and self.snapSize to determine whether/how to snap
False do not snap
Point(w,h) snap to rectangular grid with spacing (w,h)
True snap using self.snapSize (and ignoring self.translateSnap)
Also accepts *update* and *finish* arguments (see setPos() for a description of these).'
| def translate(self, *args, **kargs):
| if (len(args) == 1):
pt = args[0]
else:
pt = args
newState = self.stateCopy()
newState['pos'] = (newState['pos'] + pt)
snap = kargs.get('snap', None)
if (snap is None):
snap = self.translateSnap
if (snap is not False):
newState['pos'] = self.getSnapPosition(newState['pos'], snap=snap)
if (self.maxBounds is not None):
r = self.stateRect(newState)
d = Point(0, 0)
if (self.maxBounds.left() > r.left()):
d[0] = (self.maxBounds.left() - r.left())
elif (self.maxBounds.right() < r.right()):
d[0] = (self.maxBounds.right() - r.right())
if (self.maxBounds.top() > r.top()):
d[1] = (self.maxBounds.top() - r.top())
elif (self.maxBounds.bottom() < r.bottom()):
d[1] = (self.maxBounds.bottom() - r.bottom())
newState['pos'] += d
update = kargs.get('update', True)
finish = kargs.get('finish', True)
self.setPos(newState['pos'], update=update, finish=finish)
|
'Rotate the ROI by *angle* degrees.
Also accepts *update* and *finish* arguments (see setPos() for a
description of these).'
| def rotate(self, angle, update=True, finish=True):
| self.setAngle((self.angle() + angle), update=update, finish=finish)
|
'Add a new translation handle to the ROI. Dragging the handle will move
the entire ROI without changing its angle or shape.
Note that, by default, ROIs may be moved by dragging anywhere inside the
ROI. However, for larger ROIs it may be desirable to disable this and
instead provide one or more translation handles.
**Arguments**
pos (length-2 sequence) The position of the handle
relative to the shape of the ROI. A value of (0,0)
indicates the origin, whereas (1, 1) indicates the
upper-right corner, regardless of the ROI\'s size.
item The Handle instance to add. If None, a new handle
will be created.
name The name of this handle (optional). Handles are
identified by name when calling
getLocalHandlePositions and getSceneHandlePositions.'
| def addTranslateHandle(self, pos, axes=None, item=None, name=None, index=None):
| pos = Point(pos)
return self.addHandle({'name': name, 'type': 't', 'pos': pos, 'item': item}, index=index)
|
'Add a new free handle to the ROI. Dragging free handles has no effect
on the position or shape of the ROI.
**Arguments**
pos (length-2 sequence) The position of the handle
relative to the shape of the ROI. A value of (0,0)
indicates the origin, whereas (1, 1) indicates the
upper-right corner, regardless of the ROI\'s size.
item The Handle instance to add. If None, a new handle
will be created.
name The name of this handle (optional). Handles are
identified by name when calling
getLocalHandlePositions and getSceneHandlePositions.'
| def addFreeHandle(self, pos=None, axes=None, item=None, name=None, index=None):
| if (pos is not None):
pos = Point(pos)
return self.addHandle({'name': name, 'type': 'f', 'pos': pos, 'item': item}, index=index)
|
'Add a new scale handle to the ROI. Dragging a scale handle allows the
user to change the height and/or width of the ROI.
**Arguments**
pos (length-2 sequence) The position of the handle
relative to the shape of the ROI. A value of (0,0)
indicates the origin, whereas (1, 1) indicates the
upper-right corner, regardless of the ROI\'s size.
center (length-2 sequence) The center point around which
scaling takes place. If the center point has the
same x or y value as the handle position, then
scaling will be disabled for that axis.
item The Handle instance to add. If None, a new handle
will be created.
name The name of this handle (optional). Handles are
identified by name when calling
getLocalHandlePositions and getSceneHandlePositions.'
| def addScaleHandle(self, pos, center, axes=None, item=None, name=None, lockAspect=False, index=None):
| pos = Point(pos)
center = Point(center)
info = {'name': name, 'type': 's', 'center': center, 'pos': pos, 'item': item, 'lockAspect': lockAspect}
if (pos.x() == center.x()):
info['xoff'] = True
if (pos.y() == center.y()):
info['yoff'] = True
return self.addHandle(info, index=index)
|
'Add a new rotation handle to the ROI. Dragging a rotation handle allows
the user to change the angle of the ROI.
**Arguments**
pos (length-2 sequence) The position of the handle
relative to the shape of the ROI. A value of (0,0)
indicates the origin, whereas (1, 1) indicates the
upper-right corner, regardless of the ROI\'s size.
center (length-2 sequence) The center point around which
rotation takes place.
item The Handle instance to add. If None, a new handle
will be created.
name The name of this handle (optional). Handles are
identified by name when calling
getLocalHandlePositions and getSceneHandlePositions.'
| def addRotateHandle(self, pos, center, item=None, name=None, index=None):
| pos = Point(pos)
center = Point(center)
return self.addHandle({'name': name, 'type': 'r', 'center': center, 'pos': pos, 'item': item}, index=index)
|
'Add a new scale+rotation handle to the ROI. When dragging a handle of
this type, the user can simultaneously rotate the ROI around an
arbitrary center point as well as scale the ROI by dragging the handle
toward or away from the center point.
**Arguments**
pos (length-2 sequence) The position of the handle
relative to the shape of the ROI. A value of (0,0)
indicates the origin, whereas (1, 1) indicates the
upper-right corner, regardless of the ROI\'s size.
center (length-2 sequence) The center point around which
scaling and rotation take place.
item The Handle instance to add. If None, a new handle
will be created.
name The name of this handle (optional). Handles are
identified by name when calling
getLocalHandlePositions and getSceneHandlePositions.'
| def addScaleRotateHandle(self, pos, center, item=None, name=None, index=None):
| pos = Point(pos)
center = Point(center)
if ((pos[0] != center[0]) and (pos[1] != center[1])):
raise Exception('Scale/rotate handles must have either the same x or y coordinate as their center point.')
return self.addHandle({'name': name, 'type': 'sr', 'center': center, 'pos': pos, 'item': item}, index=index)
|
'Add a new rotation+free handle to the ROI. When dragging a handle of
this type, the user can rotate the ROI around an
arbitrary center point, while moving toward or away from the center
point has no effect on the shape of the ROI.
**Arguments**
pos (length-2 sequence) The position of the handle
relative to the shape of the ROI. A value of (0,0)
indicates the origin, whereas (1, 1) indicates the
upper-right corner, regardless of the ROI\'s size.
center (length-2 sequence) The center point around which
rotation takes place.
item The Handle instance to add. If None, a new handle
will be created.
name The name of this handle (optional). Handles are
identified by name when calling
getLocalHandlePositions and getSceneHandlePositions.'
| def addRotateFreeHandle(self, pos, center, axes=None, item=None, name=None, index=None):
| pos = Point(pos)
center = Point(center)
return self.addHandle({'name': name, 'type': 'rf', 'center': center, 'pos': pos, 'item': item}, index=index)
|
'Return the index of *handle* in the list of this ROI\'s handles.'
| def indexOfHandle(self, handle):
| if isinstance(handle, Handle):
index = [i for (i, info) in enumerate(self.handles) if (info['item'] is handle)]
if (len(index) == 0):
raise Exception('Cannot return handle index; not attached to this ROI')
return index[0]
else:
return handle
|
'Remove a handle from this ROI. Argument may be either a Handle
instance or the integer index of the handle.'
| def removeHandle(self, handle):
| index = self.indexOfHandle(handle)
handle = self.handles[index]['item']
self.handles.pop(index)
handle.disconnectROI(self)
if (len(handle.rois) == 0):
self.scene().removeItem(handle)
self.stateChanged()
|
'Replace one handle in the ROI for another. This is useful when
connecting multiple ROIs together.
*oldHandle* may be a Handle instance or the index of a handle to be
replaced.'
| def replaceHandle(self, oldHandle, newHandle):
| index = self.indexOfHandle(oldHandle)
info = self.handles[index]
self.removeHandle(index)
info['item'] = newHandle
info['pos'] = newHandle.pos()
self.addHandle(info, index=index)
|
'Returns the position of handles in the ROI\'s coordinate system.
The format returned is a list of (name, pos) tuples.'
| def getLocalHandlePositions(self, index=None):
| if (index == None):
positions = []
for h in self.handles:
positions.append((h['name'], h['pos']))
return positions
else:
return (self.handles[index]['name'], self.handles[index]['pos'])
|
'Returns the position of handles in the scene coordinate system.
The format returned is a list of (name, pos) tuples.'
| def getSceneHandlePositions(self, index=None):
| if (index == None):
positions = []
for h in self.handles:
positions.append((h['name'], h['item'].scenePos()))
return positions
else:
return (self.handles[index]['name'], self.handles[index]['item'].scenePos())
|
'Return a list of this ROI\'s Handles.'
| def getHandles(self):
| return [h['item'] for h in self.handles]
|
'When handles move, they must ask the ROI if the move is acceptable.
By default, this always returns True. Subclasses may wish override.'
| def checkPointMove(self, handle, pos, modifiers):
| return True
|
'Process changes to the state of the ROI.
If there are any changes, then the positions of handles are updated accordingly
and sigRegionChanged is emitted. If finish is True, then
sigRegionChangeFinished will also be emitted.'
| def stateChanged(self, finish=True):
| changed = False
if (self.lastState is None):
changed = True
else:
state = self.getState()
for k in list(state.keys()):
if (state[k] != self.lastState[k]):
changed = True
self.prepareGeometryChange()
if changed:
for h in self.handles:
if (h['item'] in self.childItems()):
p = h['pos']
h['item'].setPos((h['pos'] * self.state['size']))
self.update()
self.sigRegionChanged.emit(self)
elif self.freeHandleMoved:
self.sigRegionChanged.emit(self)
self.freeHandleMoved = False
self.lastState = self.getState()
if finish:
self.stateChangeFinished()
self.informViewBoundsChanged()
|
'Return a tuple of slice objects that can be used to slice the region
from *data* that is covered by the bounding rectangle of this ROI.
Also returns the transform that maps the ROI into data coordinates.
If returnSlice is set to False, the function returns a pair of tuples with the values that would have
been used to generate the slice objects. ((ax0Start, ax0Stop), (ax1Start, ax1Stop))
If the slice cannot be computed (usually because the scene/transforms are not properly
constructed yet), then the method returns None.'
| def getArraySlice(self, data, img, axes=(0, 1), returnSlice=True):
| dShape = (data.shape[axes[0]], data.shape[axes[1]])
try:
tr = (self.sceneTransform() * fn.invertQTransform(img.sceneTransform()))
except np.linalg.linalg.LinAlgError:
return None
axisOrder = img.axisOrder
if (axisOrder == 'row-major'):
tr.scale((float(dShape[1]) / img.width()), (float(dShape[0]) / img.height()))
else:
tr.scale((float(dShape[0]) / img.width()), (float(dShape[1]) / img.height()))
dataBounds = tr.mapRect(self.boundingRect())
if (axisOrder == 'row-major'):
intBounds = dataBounds.intersected(QtCore.QRectF(0, 0, dShape[1], dShape[0]))
else:
intBounds = dataBounds.intersected(QtCore.QRectF(0, 0, dShape[0], dShape[1]))
bounds = ((int(min(intBounds.left(), intBounds.right())), int((1 + max(intBounds.left(), intBounds.right())))), (int(min(intBounds.bottom(), intBounds.top())), int((1 + max(intBounds.bottom(), intBounds.top())))))
if (axisOrder == 'row-major'):
bounds = bounds[::(-1)]
if returnSlice:
sl = ([slice(None)] * data.ndim)
sl[axes[0]] = slice(*bounds[0])
sl[axes[1]] = slice(*bounds[1])
return (tuple(sl), tr)
else:
return (bounds, tr)
|
'Use the position and orientation of this ROI relative to an imageItem
to pull a slice from an array.
**Arguments**
data The array to slice from. Note that this array does
*not* have to be the same data that is represented
in *img*.
img (ImageItem or other suitable QGraphicsItem)
Used to determine the relationship between the
ROI and the boundaries of *data*.
axes (length-2 tuple) Specifies the axes in *data* that
correspond to the (x, y) axes of *img*. If the
image\'s axis order is set to
\'row-major\', then the axes are instead specified in
(y, x) order.
returnMappedCoords (bool) If True, the array slice is returned along
with a corresponding array of coordinates that were
used to extract data from the original array.
\**kwds All keyword arguments are passed to
:func:`affineSlice <pyqtgraph.affineSlice>`.
This method uses :func:`affineSlice <pyqtgraph.affineSlice>` to generate
the slice from *data* and uses :func:`getAffineSliceParams <pyqtgraph.ROI.getAffineSliceParams>`
to determine the parameters to pass to :func:`affineSlice <pyqtgraph.affineSlice>`.
If *returnMappedCoords* is True, then the method returns a tuple (result, coords)
such that coords is the set of coordinates used to interpolate values from the original
data, mapped into the parent coordinate system of the image. This is useful, when slicing
data from images that have been transformed, for determining the location of each value
in the sliced data.
All extra keyword arguments are passed to :func:`affineSlice <pyqtgraph.affineSlice>`.'
| def getArrayRegion(self, data, img, axes=(0, 1), returnMappedCoords=False, **kwds):
| fromBR = kwds.pop('fromBoundingRect', False)
(shape, vectors, origin) = self.getAffineSliceParams(data, img, axes, fromBoundingRect=fromBR)
if (not returnMappedCoords):
rgn = fn.affineSlice(data, shape=shape, vectors=vectors, origin=origin, axes=axes, **kwds)
return rgn
else:
kwds['returnCoords'] = True
(result, coords) = fn.affineSlice(data, shape=shape, vectors=vectors, origin=origin, axes=axes, **kwds)
mapped = fn.transformCoordinates(img.transform(), coords)
return (result, mapped)
|
'Returns the parameters needed to use :func:`affineSlice <pyqtgraph.affineSlice>`
(shape, vectors, origin) to extract a subset of *data* using this ROI
and *img* to specify the subset.
If *fromBoundingRect* is True, then the ROI\'s bounding rectangle is used
rather than the shape of the ROI.
See :func:`getArrayRegion <pyqtgraph.ROI.getArrayRegion>` for more information.'
| def getAffineSliceParams(self, data, img, axes=(0, 1), fromBoundingRect=False):
| if (self.scene() is not img.scene()):
raise Exception('ROI and target item must be members of the same scene.')
origin = img.mapToData(self.mapToItem(img, QtCore.QPointF(0, 0)))
vx = (img.mapToData(self.mapToItem(img, QtCore.QPointF(1, 0))) - origin)
vy = (img.mapToData(self.mapToItem(img, QtCore.QPointF(0, 1))) - origin)
lvx = np.sqrt(((vx.x() ** 2) + (vx.y() ** 2)))
lvy = np.sqrt(((vy.x() ** 2) + (vy.y() ** 2)))
sx = (1.0 / lvx)
sy = (1.0 / lvy)
vectors = (((vx.x() * sx), (vx.y() * sx)), ((vy.x() * sy), (vy.y() * sy)))
if (fromBoundingRect is True):
shape = (self.boundingRect().width(), self.boundingRect().height())
origin = img.mapToData(self.mapToItem(img, self.boundingRect().topLeft()))
origin = (origin.x(), origin.y())
else:
shape = self.state['size']
origin = (origin.x(), origin.y())
shape = [abs((shape[0] / sx)), abs((shape[1] / sy))]
if (img.axisOrder == 'row-major'):
vectors = vectors[::(-1)]
shape = shape[::(-1)]
return (shape, vectors, origin)
|
'Return an array of 0.0-1.0 into which the shape of the item has been drawn.
This can be used to mask array selections.'
| def renderShapeMask(self, width, height):
| if ((width == 0) or (height == 0)):
return np.empty((width, height), dtype=float)
im = QtGui.QImage(width, height, QtGui.QImage.Format_ARGB32)
im.fill(0)
p = QtGui.QPainter(im)
p.setPen(fn.mkPen(None))
p.setBrush(fn.mkBrush('w'))
shape = self.shape()
bounds = shape.boundingRect()
p.scale((im.width() / bounds.width()), (im.height() / bounds.height()))
p.translate((- bounds.topLeft()))
p.drawPath(shape)
p.end()
mask = (fn.imageToArray(im, transpose=True)[:, :, 0].astype(float) / 255.0)
return mask
|
'Return global transformation (rotation angle+translation) required to move
from relative state to current state. If relative state isn\'t specified,
then we use the state of the ROI when mouse is pressed.'
| def getGlobalTransform(self, relativeTo=None):
| if (relativeTo == None):
relativeTo = self.preMoveState
st = self.getState()
relativeTo['scale'] = relativeTo['size']
st['scale'] = st['size']
t1 = SRTTransform(relativeTo)
t2 = SRTTransform(st)
return (t2 / t1)
|
'Return the positions of all handles in local coordinates.'
| def getHandlePositions(self):
| pos = [self.mapFromScene(self.lines[0].getHandles()[0].scenePos())]
for l in self.lines:
pos.append(self.mapFromScene(l.getHandles()[1].scenePos()))
return pos
|
'Add a new segment to the ROI connecting from the previous endpoint to *pos*.
(pos is specified in the parent coordinate system of the MultiRectROI)'
| def addSegment(self, pos=(0, 0), scaleHandle=False, connectTo=None):
| if (connectTo is None):
connectTo = self.lines[(-1)].getHandles()[1]
newRoi = ROI((0, 0), [1, 5], parent=self, pen=self.pen, **self.roiArgs)
self.lines.append(newRoi)
if isinstance(connectTo, Handle):
self.lines[(-1)].addScaleRotateHandle([0, 0.5], [1, 0.5], item=connectTo)
newRoi.movePoint(connectTo, connectTo.scenePos(), coords='scene')
else:
h = self.lines[(-1)].addScaleRotateHandle([0, 0.5], [1, 0.5])
newRoi.movePoint(h, connectTo, coords='scene')
h = self.lines[(-1)].addScaleRotateHandle([1, 0.5], [0, 0.5])
newRoi.movePoint(h, pos)
if scaleHandle:
newRoi.addScaleHandle([0.5, 1], [0.5, 0.5])
newRoi.translatable = False
newRoi.sigRegionChanged.connect(self.roiChangedEvent)
newRoi.sigRegionChangeStarted.connect(self.roiChangeStartedEvent)
newRoi.sigRegionChangeFinished.connect(self.roiChangeFinishedEvent)
self.sigRegionChanged.emit(self)
|
'Remove a segment from the ROI.'
| def removeSegment(self, index=(-1)):
| roi = self.lines[index]
self.lines.pop(index)
self.scene().removeItem(roi)
roi.sigRegionChanged.disconnect(self.roiChangedEvent)
roi.sigRegionChangeStarted.disconnect(self.roiChangeStartedEvent)
roi.sigRegionChangeFinished.disconnect(self.roiChangeFinishedEvent)
self.sigRegionChanged.emit(self)
|
'Return the result of ROI.getArrayRegion() masked by the elliptical shape
of the ROI. Regions outside the ellipse are set to 0.'
| def getArrayRegion(self, arr, img=None, axes=(0, 1), **kwds):
| arr = ROI.getArrayRegion(self, arr, img, axes, **kwds)
if ((arr is None) or (arr.shape[axes[0]] == 0) or (arr.shape[axes[1]] == 0)):
return arr
w = arr.shape[axes[0]]
h = arr.shape[axes[1]]
mask = np.fromfunction((lambda x, y: (((((((x + 0.5) / (w / 2.0)) - 1) ** 2) + ((((y + 0.5) / (h / 2.0)) - 1) ** 2)) ** 0.5) < 1)), (w, h))
if (axes[0] > axes[1]):
mask = mask.T
shape = [(n if (i in axes) else 1) for (i, n) in enumerate(arr.shape)]
mask = mask.reshape(shape)
return (arr * mask)
|
'Set the complete sequence of points displayed by this ROI.
**Arguments**
points List of (x,y) tuples specifying handle locations to set.
closed If bool, then this will set whether the ROI is closed
(the last point is connected to the first point). If
None, then the closed mode is left unchanged.'
| def setPoints(self, points, closed=None):
| if (closed is not None):
self.closed = closed
self.clearPoints()
for p in points:
self.addFreeHandle(p)
start = ((-1) if self.closed else 0)
for i in range(start, (len(self.handles) - 1)):
self.addSegment(self.handles[i]['item'], self.handles[(i + 1)]['item'])
|
'Remove all handles and segments.'
| def clearPoints(self):
| while (len(self.handles) > 0):
self.removeHandle(self.handles[0]['item'])
|
'Return the result of ROI.getArrayRegion(), masked by the shape of the
ROI. Values outside the ROI shape are set to 0.'
| def getArrayRegion(self, data, img, axes=(0, 1), **kwds):
| br = self.boundingRect()
if (br.width() > 1000):
raise Exception()
sliced = ROI.getArrayRegion(self, data, img, axes=axes, fromBoundingRect=True, **kwds)
if (img.axisOrder == 'col-major'):
mask = self.renderShapeMask(sliced.shape[axes[0]], sliced.shape[axes[1]])
else:
mask = self.renderShapeMask(sliced.shape[axes[1]], sliced.shape[axes[0]])
mask = mask.T
shape = ([1] * data.ndim)
shape[axes[0]] = sliced.shape[axes[0]]
shape[axes[1]] = sliced.shape[axes[1]]
mask = mask.reshape(shape)
return (sliced * mask)
|
'Use the position of this ROI relative to an imageItem to pull a slice
from an array.
Since this pulls 1D data from a 2D coordinate system, the return value
will have ndim = data.ndim-1
See ROI.getArrayRegion() for a description of the arguments.'
| def getArrayRegion(self, data, img, axes=(0, 1), order=1, returnMappedCoords=False, **kwds):
| imgPts = [self.mapToItem(img, h.pos()) for h in self.endpoints]
rgns = []
coords = []
d = Point((imgPts[1] - imgPts[0]))
o = Point(imgPts[0])
rgn = fn.affineSlice(data, shape=(int(d.length()),), vectors=[Point(d.norm())], origin=o, axes=axes, order=order, returnCoords=returnMappedCoords, **kwds)
return rgn
|
'Change the data displayed by the graph.
**Arguments:**
pos (N,2) array of the positions of each node in the graph.
adj (M,2) array of connection data. Each row contains indexes
of two nodes that are connected.
pen The pen to use when drawing lines between connected
nodes. May be one of:
* QPen
* a single argument to pass to pg.mkPen
* a record array of length M
with fields (red, green, blue, alpha, width). Note
that using this option may have a significant performance
cost.
* None (to disable connection drawing)
* \'default\' to use the default foreground color.
symbolPen The pen(s) used for drawing nodes.
symbolBrush The brush(es) used for drawing nodes.
``**opts`` All other keyword arguments are given to
:func:`ScatterPlotItem.setData() <pyqtgraph.ScatterPlotItem.setData>`
to affect the appearance of nodes (symbol, size, brush,
etc.)'
| def setData(self, **kwds):
| if ('adj' in kwds):
self.adjacency = kwds.pop('adj')
if (self.adjacency.dtype.kind not in 'iu'):
raise Exception('adjacency array must have int or unsigned type.')
self._update()
if ('pos' in kwds):
self.pos = kwds['pos']
self._update()
if ('pen' in kwds):
self.setPen(kwds.pop('pen'))
self._update()
if ('symbolPen' in kwds):
kwds['pen'] = kwds.pop('symbolPen')
if ('symbolBrush' in kwds):
kwds['brush'] = kwds.pop('symbolBrush')
self.scatter.setData(**kwds)
self.informViewBoundsChanged()
|
'Set the pen used to draw graph lines.
May be:
* None to disable line drawing
* Record array with fields (red, green, blue, alpha, width)
* Any set of arguments and keyword arguments accepted by
:func:`mkPen <pyqtgraph.mkPen>`.
* \'default\' to use the default foreground color.'
| def setPen(self, *args, **kwargs):
| if ((len(args) == 1) and (len(kwargs) == 0)):
self.pen = args[0]
else:
self.pen = fn.mkPen(*args, **kwargs)
self.picture = None
self.update()
|
'**Bases:** :class:`GraphicsItem <pyqtgraph.GraphicsItem>`, :class:`QtGui.QGraphicsWidget`
Extends QGraphicsWidget with several helpful methods and workarounds for PyQt bugs.
Most of the extra functionality is inherited from :class:`GraphicsItem <pyqtgraph.GraphicsItem>`.'
| def __init__(self, *args, **kargs):
| QtGui.QGraphicsWidget.__init__(self, *args, **kargs)
GraphicsItem.__init__(self)
|
'There are many different ways to create a PlotDataItem:
**Data initialization arguments:** (x,y data only)
PlotDataItem(xValues, yValues) x and y values may be any sequence (including ndarray) of real numbers
PlotDataItem(yValues) y values only -- x will be automatically set to range(len(y))
PlotDataItem(x=xValues, y=yValues) x and y given by keyword arguments
PlotDataItem(ndarray(Nx2)) numpy array with shape (N, 2) where x=data[:,0] and y=data[:,1]
**Data initialization arguments:** (x,y data AND may include spot style)
PlotDataItem(recarray) numpy array with dtype=[(\'x\', float), (\'y\', float), ...]
PlotDataItem(list-of-dicts) [{\'x\': x, \'y\': y, ...}, ...]
PlotDataItem(dict-of-lists) {\'x\': [...], \'y\': [...], ...}
PlotDataItem(MetaArray) 1D array of Y values with X sepecified as axis values
OR 2D array with a column \'y\' and extra columns as needed.
**Line style keyword arguments:**
connect Specifies how / whether vertexes should be connected. See
:func:`arrayToQPath() <pyqtgraph.arrayToQPath>`
pen Pen to use for drawing line between points.
Default is solid grey, 1px width. Use None to disable line drawing.
May be any single argument accepted by :func:`mkPen() <pyqtgraph.mkPen>`
shadowPen Pen for secondary line to draw behind the primary line. disabled by default.
May be any single argument accepted by :func:`mkPen() <pyqtgraph.mkPen>`
fillLevel Fill the area between the curve and fillLevel
fillBrush Fill to use when fillLevel is specified.
May be any single argument accepted by :func:`mkBrush() <pyqtgraph.mkBrush>`
stepMode If True, two orthogonal lines are drawn for each sample
as steps. This is commonly used when drawing histograms.
Note that in this case, `len(x) == len(y) + 1`
(added in version 0.9.9)
**Point style keyword arguments:** (see :func:`ScatterPlotItem.setData() <pyqtgraph.ScatterPlotItem.setData>` for more information)
symbol Symbol to use for drawing points OR list of symbols,
one per point. Default is no symbol.
Options are o, s, t, d, +, or any QPainterPath
symbolPen Outline pen for drawing points OR list of pens, one
per point. May be any single argument accepted by
:func:`mkPen() <pyqtgraph.mkPen>`
symbolBrush Brush for filling points OR list of brushes, one per
point. May be any single argument accepted by
:func:`mkBrush() <pyqtgraph.mkBrush>`
symbolSize Diameter of symbols OR list of diameters.
pxMode (bool) If True, then symbolSize is specified in
pixels. If False, then symbolSize is
specified in data coordinates.
**Optimization keyword arguments:**
antialias (bool) By default, antialiasing is disabled to improve performance.
Note that in some cases (in particluar, when pxMode=True), points
will be rendered antialiased even if this is set to False.
decimate deprecated.
downsample (int) Reduce the number of samples displayed by this value
downsampleMethod \'subsample\': Downsample by taking the first of N samples.
This method is fastest and least accurate.
\'mean\': Downsample by taking the mean of N samples.
\'peak\': Downsample by drawing a saw wave that follows the min
and max of the original data. This method produces the best
visual representation of the data but is slower.
autoDownsample (bool) If True, resample the data before plotting to avoid plotting
multiple line segments per pixel. This can improve performance when
viewing very high-density data, but increases the initial overhead
and memory usage.
clipToView (bool) If True, only plot data that is visible within the X range of
the containing ViewBox. This can improve performance when plotting
very large data sets where only a fraction of the data is visible
at any time.
identical *deprecated*
**Meta-info keyword arguments:**
name name of dataset. This would appear in a legend'
| def __init__(self, *args, **kargs):
| GraphicsObject.__init__(self)
self.setFlag(self.ItemHasNoContents)
self.xData = None
self.yData = None
self.xDisp = None
self.yDisp = None
self.curve = PlotCurveItem()
self.scatter = ScatterPlotItem()
self.curve.setParentItem(self)
self.scatter.setParentItem(self)
self.curve.sigClicked.connect(self.curveClicked)
self.scatter.sigClicked.connect(self.scatterClicked)
self.opts = {'connect': 'all', 'fftMode': False, 'logMode': [False, False], 'alphaHint': 1.0, 'alphaMode': False, 'pen': (200, 200, 200), 'shadowPen': None, 'fillLevel': None, 'fillBrush': None, 'stepMode': None, 'symbol': None, 'symbolSize': 10, 'symbolPen': (200, 200, 200), 'symbolBrush': (50, 50, 150), 'pxMode': True, 'antialias': getConfigOption('antialias'), 'pointMode': None, 'downsample': 1, 'autoDownsample': False, 'downsampleMethod': 'peak', 'autoDownsampleFactor': 5.0, 'clipToView': False, 'data': None}
self.setData(*args, **kargs)
|
'| Sets the pen used to draw lines between points.
| *pen* can be a QPen or any argument accepted by :func:`pyqtgraph.mkPen() <pyqtgraph.mkPen>`'
| def setPen(self, *args, **kargs):
| pen = fn.mkPen(*args, **kargs)
self.opts['pen'] = pen
self.updateItems()
|
'| Sets the shadow pen used to draw lines between points (this is for enhancing contrast or
emphacizing data).
| This line is drawn behind the primary pen (see :func:`setPen() <pyqtgraph.PlotDataItem.setPen>`)
and should generally be assigned greater width than the primary pen.
| *pen* can be a QPen or any argument accepted by :func:`pyqtgraph.mkPen() <pyqtgraph.mkPen>`'
| def setShadowPen(self, *args, **kargs):
| pen = fn.mkPen(*args, **kargs)
self.opts['shadowPen'] = pen
self.updateItems()
|
'Set the downsampling mode of this item. Downsampling reduces the number
of samples drawn to increase performance.
**Arguments:**
ds (int) Reduce visible plot samples by this factor. To disable,
set ds=1.
auto (bool) If True, automatically pick *ds* based on visible range
mode \'subsample\': Downsample by taking the first of N samples.
This method is fastest and least accurate.
\'mean\': Downsample by taking the mean of N samples.
\'peak\': Downsample by drawing a saw wave that follows the min
and max of the original data. This method produces the best
visual representation of the data but is slower.'
| def setDownsampling(self, ds=None, auto=None, method=None):
| changed = False
if (ds is not None):
if (self.opts['downsample'] != ds):
changed = True
self.opts['downsample'] = ds
if ((auto is not None) and (self.opts['autoDownsample'] != auto)):
self.opts['autoDownsample'] = auto
changed = True
if (method is not None):
if (self.opts['downsampleMethod'] != method):
changed = True
self.opts['downsampleMethod'] = method
if changed:
self.xDisp = self.yDisp = None
self.updateItems()
|
'Clear any data displayed by this item and display new data.
See :func:`__init__() <pyqtgraph.PlotDataItem.__init__>` for details; it accepts the same arguments.'
| def setData(self, *args, **kargs):
| profiler = debug.Profiler()
y = None
x = None
if (len(args) == 1):
data = args[0]
dt = dataType(data)
if (dt == 'empty'):
pass
elif (dt == 'listOfValues'):
y = np.array(data)
elif (dt == 'Nx2array'):
x = data[:, 0]
y = data[:, 1]
elif ((dt == 'recarray') or (dt == 'dictOfLists')):
if ('x' in data):
x = np.array(data['x'])
if ('y' in data):
y = np.array(data['y'])
elif (dt == 'listOfDicts'):
if ('x' in data[0]):
x = np.array([d.get('x', None) for d in data])
if ('y' in data[0]):
y = np.array([d.get('y', None) for d in data])
for k in ['data', 'symbolSize', 'symbolPen', 'symbolBrush', 'symbolShape']:
if (k in data):
kargs[k] = [d.get(k, None) for d in data]
elif (dt == 'MetaArray'):
y = data.view(np.ndarray)
x = data.xvals(0).view(np.ndarray)
else:
raise Exception(('Invalid data type %s' % type(data)))
elif (len(args) == 2):
seq = ('listOfValues', 'MetaArray', 'empty')
dtyp = (dataType(args[0]), dataType(args[1]))
if ((dtyp[0] not in seq) or (dtyp[1] not in seq)):
raise Exception(('When passing two unnamed arguments, both must be a list or array of values. (got %s, %s)' % (str(type(args[0])), str(type(args[1])))))
if (not isinstance(args[0], np.ndarray)):
if (dtyp[0] == 'MetaArray'):
x = args[0].asarray()
else:
x = np.array(args[0])
else:
x = args[0].view(np.ndarray)
if (not isinstance(args[1], np.ndarray)):
if (dtyp[1] == 'MetaArray'):
y = args[1].asarray()
else:
y = np.array(args[1])
else:
y = args[1].view(np.ndarray)
if ('x' in kargs):
x = kargs['x']
if ('y' in kargs):
y = kargs['y']
profiler('interpret data')
if ('name' in kargs):
self.opts['name'] = kargs['name']
if ('connect' in kargs):
self.opts['connect'] = kargs['connect']
if (('symbol' not in kargs) and (('symbolPen' in kargs) or ('symbolBrush' in kargs) or ('symbolSize' in kargs))):
kargs['symbol'] = 'o'
if ('brush' in kargs):
kargs['fillBrush'] = kargs['brush']
for k in list(self.opts.keys()):
if (k in kargs):
self.opts[k] = kargs[k]
if (y is None):
return
if ((y is not None) and (x is None)):
x = np.arange(len(y))
if isinstance(x, list):
x = np.array(x)
if isinstance(y, list):
y = np.array(y)
self.xData = x.view(np.ndarray)
self.yData = y.view(np.ndarray)
self.xClean = self.yClean = None
self.xDisp = None
self.yDisp = None
profiler('set data')
self.updateItems()
profiler('update items')
self.informViewBoundsChanged()
self.sigPlotChanged.emit(self)
profiler('emit')
|
'Returns the range occupied by the data (along a specific axis) in this item.
This method is called by ViewBox when auto-scaling.
**Arguments:**
ax (0 or 1) the axis for which to return this item\'s data range
frac (float 0.0-1.0) Specifies what fraction of the total data
range to return. By default, the entire range is returned.
This allows the ViewBox to ignore large spikes in the data
when auto-scaling.
orthoRange ([min,max] or None) Specifies that only the data within the
given range (orthogonal to *ax*) should me measured when
returning the data range. (For example, a ViewBox might ask
what is the y-range of all data with x-values between min
and max)'
| def dataBounds(self, ax, frac=1.0, orthoRange=None):
| range = [None, None]
if self.curve.isVisible():
range = self.curve.dataBounds(ax, frac, orthoRange)
elif self.scatter.isVisible():
r2 = self.scatter.dataBounds(ax, frac, orthoRange)
range = [(r2[0] if (range[0] is None) else (range[0] if (r2[0] is None) else min(r2[0], range[0]))), (r2[1] if (range[1] is None) else (range[1] if (r2[1] is None) else min(r2[1], range[1])))]
return range
|
'Return the size in pixels that this item may draw beyond the values returned by dataBounds().
This method is called by ViewBox when auto-scaling.'
| def pixelPadding(self):
| pad = 0
if self.curve.isVisible():
pad = max(pad, self.curve.pixelPadding())
elif self.scatter.isVisible():
pad = max(pad, self.scatter.pixelPadding())
return pad
|
'**Arguments:**
orientation Set the orientation of the gradient. Options are: \'left\', \'right\'
\'top\', and \'bottom\'.
allowAdd Specifies whether ticks can be added to the item by the user.
tickPen Default is white. Specifies the color of the outline of the ticks.
Can be any of the valid arguments for :func:`mkPen <pyqtgraph.mkPen>`'
| def __init__(self, orientation='bottom', allowAdd=True, **kargs):
| GraphicsWidget.__init__(self)
self.orientation = orientation
self.length = 100
self.tickSize = 15
self.ticks = {}
self.maxDim = 20
self.allowAdd = allowAdd
if ('tickPen' in kargs):
self.tickPen = fn.mkPen(kargs['tickPen'])
else:
self.tickPen = fn.mkPen('w')
self.orientations = {'left': (90, 1, 1), 'right': (90, 1, 1), 'top': (0, 1, (-1)), 'bottom': (0, 1, 1)}
self.setOrientation(orientation)
|
'Set the orientation of the TickSliderItem.
**Arguments:**
orientation Options are: \'left\', \'right\', \'top\', \'bottom\'
The orientation option specifies which side of the slider the
ticks are on, as well as whether the slider is vertical (\'right\'
and \'left\') or horizontal (\'top\' and \'bottom\').'
| def setOrientation(self, orientation):
| self.orientation = orientation
self.setMaxDim()
self.resetTransform()
ort = orientation
if (ort == 'top'):
transform = QtGui.QTransform.fromScale(1, (-1))
transform.translate(0, (- self.height()))
self.setTransform(transform)
elif (ort == 'left'):
transform = QtGui.QTransform()
transform.rotate(270)
transform.scale(1, (-1))
transform.translate((- self.height()), (- self.maxDim))
self.setTransform(transform)
elif (ort == 'right'):
transform = QtGui.QTransform()
transform.rotate(270)
transform.translate((- self.height()), 0)
self.setTransform(transform)
elif (ort != 'bottom'):
raise Exception(("%s is not a valid orientation. Options are 'left', 'right', 'top', and 'bottom'" % str(ort)))
self.translate((self.tickSize / 2.0), 0)
|
'Add a tick to the item.
**Arguments:**
x Position where tick should be added.
color Color of added tick. If color is not specified, the color will be
white.
movable Specifies whether the tick is movable with the mouse.'
| def addTick(self, x, color=None, movable=True):
| if (color is None):
color = QtGui.QColor(255, 255, 255)
tick = Tick(self, [(x * self.length), 0], color, movable, self.tickSize, pen=self.tickPen)
self.ticks[tick] = x
tick.setParentItem(self)
return tick
|
'Removes the specified tick.'
| def removeTick(self, tick):
| del self.ticks[tick]
tick.setParentItem(None)
if (self.scene() is not None):
self.scene().removeItem(tick)
|
'Set the color of the specified tick.
**Arguments:**
tick Can be either an integer corresponding to the index of the tick
or a Tick object. Ex: if you had a slider with 3 ticks and you
wanted to change the middle tick, the index would be 1.
color The color to make the tick. Can be any argument that is valid for
:func:`mkBrush <pyqtgraph.mkBrush>`'
| def setTickColor(self, tick, color):
| tick = self.getTick(tick)
tick.color = color
tick.update()
|
'Set the position (along the slider) of the tick.
**Arguments:**
tick Can be either an integer corresponding to the index of the tick
or a Tick object. Ex: if you had a slider with 3 ticks and you
wanted to change the middle tick, the index would be 1.
val The desired position of the tick. If val is < 0, position will be
set to 0. If val is > 1, position will be set to 1.'
| def setTickValue(self, tick, val):
| tick = self.getTick(tick)
val = min(max(0.0, val), 1.0)
x = (val * self.length)
pos = tick.pos()
pos.setX(x)
tick.setPos(pos)
self.ticks[tick] = val
self.updateGradient()
|
'Return the value (from 0.0 to 1.0) of the specified tick.
**Arguments:**
tick Can be either an integer corresponding to the index of the tick
or a Tick object. Ex: if you had a slider with 3 ticks and you
wanted the value of the middle tick, the index would be 1.'
| def tickValue(self, tick):
| tick = self.getTick(tick)
return self.ticks[tick]
|
'Return the Tick object at the specified index.
**Arguments:**
tick An integer corresponding to the index of the desired tick. If the
argument is not an integer it will be returned unchanged.'
| def getTick(self, tick):
| if (type(tick) is int):
tick = self.listTicks()[tick][0]
return tick
|
'Return a sorted list of all the Tick objects on the slider.'
| def listTicks(self):
| ticks = list(self.ticks.items())
sortList(ticks, (lambda a, b: cmp(a[1], b[1])))
return ticks
|
'Create a new GradientEditorItem.
All arguments are passed to :func:`TickSliderItem.__init__ <pyqtgraph.TickSliderItem.__init__>`
**Arguments:**
orientation Set the orientation of the gradient. Options are: \'left\', \'right\'
\'top\', and \'bottom\'.
allowAdd Default is True. Specifies whether ticks can be added to the item.
tickPen Default is white. Specifies the color of the outline of the ticks.
Can be any of the valid arguments for :func:`mkPen <pyqtgraph.mkPen>`'
| def __init__(self, *args, **kargs):
| self.currentTick = None
self.currentTickColor = None
self.rectSize = 15
self.gradRect = QtGui.QGraphicsRectItem(QtCore.QRectF(0, self.rectSize, 100, self.rectSize))
self.backgroundRect = QtGui.QGraphicsRectItem(QtCore.QRectF(0, (- self.rectSize), 100, self.rectSize))
self.backgroundRect.setBrush(QtGui.QBrush(QtCore.Qt.DiagCrossPattern))
self.colorMode = 'rgb'
TickSliderItem.__init__(self, *args, **kargs)
self.colorDialog = QtGui.QColorDialog()
self.colorDialog.setOption(QtGui.QColorDialog.ShowAlphaChannel, True)
self.colorDialog.setOption(QtGui.QColorDialog.DontUseNativeDialog, True)
self.colorDialog.currentColorChanged.connect(self.currentColorChanged)
self.colorDialog.rejected.connect(self.currentColorRejected)
self.colorDialog.accepted.connect(self.currentColorAccepted)
self.backgroundRect.setParentItem(self)
self.gradRect.setParentItem(self)
self.setMaxDim((self.rectSize + self.tickSize))
self.rgbAction = QtGui.QAction('RGB', self)
self.rgbAction.setCheckable(True)
self.rgbAction.triggered.connect((lambda : self.setColorMode('rgb')))
self.hsvAction = QtGui.QAction('HSV', self)
self.hsvAction.setCheckable(True)
self.hsvAction.triggered.connect((lambda : self.setColorMode('hsv')))
self.menu = QtGui.QMenu()
l = self.length
self.length = 100
global Gradients
for g in Gradients:
px = QtGui.QPixmap(100, 15)
p = QtGui.QPainter(px)
self.restoreState(Gradients[g])
grad = self.getGradient()
brush = QtGui.QBrush(grad)
p.fillRect(QtCore.QRect(0, 0, 100, 15), brush)
p.end()
label = QtGui.QLabel()
label.setPixmap(px)
label.setContentsMargins(1, 1, 1, 1)
act = QtGui.QWidgetAction(self)
act.setDefaultWidget(label)
act.triggered.connect(self.contextMenuClicked)
act.name = g
self.menu.addAction(act)
self.length = l
self.menu.addSeparator()
self.menu.addAction(self.rgbAction)
self.menu.addAction(self.hsvAction)
for t in list(self.ticks.keys()):
self.removeTick(t)
self.addTick(0, QtGui.QColor(0, 0, 0), True)
self.addTick(1, QtGui.QColor(255, 0, 0), True)
self.setColorMode('rgb')
self.updateGradient()
|
'Set the orientation of the GradientEditorItem.
**Arguments:**
orientation Options are: \'left\', \'right\', \'top\', \'bottom\'
The orientation option specifies which side of the gradient the
ticks are on, as well as whether the gradient is vertical (\'right\'
and \'left\') or horizontal (\'top\' and \'bottom\').'
| def setOrientation(self, orientation):
| TickSliderItem.setOrientation(self, orientation)
self.translate(0, self.rectSize)
|
'Load a predefined gradient. Currently defined gradients are:'
| @addGradientListToDocstring()
def loadPreset(self, name):
| self.restoreState(Gradients[name])
|
'Set the color mode for the gradient. Options are: \'hsv\', \'rgb\''
| def setColorMode(self, cm):
| if (cm not in ['rgb', 'hsv']):
raise Exception(("Unknown color mode %s. Options are 'rgb' and 'hsv'." % str(cm)))
try:
self.rgbAction.blockSignals(True)
self.hsvAction.blockSignals(True)
self.rgbAction.setChecked((cm == 'rgb'))
self.hsvAction.setChecked((cm == 'hsv'))
finally:
self.rgbAction.blockSignals(False)
self.hsvAction.blockSignals(False)
self.colorMode = cm
self.updateGradient()
|
'Return a ColorMap object representing the current state of the editor.'
| def colorMap(self):
| if (self.colorMode == 'hsv'):
raise NotImplementedError('hsv colormaps not yet supported')
pos = []
color = []
for (t, x) in self.listTicks():
pos.append(x)
c = t.color
color.append([c.red(), c.green(), c.blue(), c.alpha()])
return ColorMap(np.array(pos), np.array(color, dtype=np.ubyte))
|
'Return a QLinearGradient object.'
| def getGradient(self):
| g = QtGui.QLinearGradient(QtCore.QPointF(0, 0), QtCore.QPointF(self.length, 0))
if (self.colorMode == 'rgb'):
ticks = self.listTicks()
g.setStops([(x, QtGui.QColor(t.color)) for (t, x) in ticks])
elif (self.colorMode == 'hsv'):
ticks = self.listTicks()
stops = []
stops.append((ticks[0][1], ticks[0][0].color))
for i in range(1, len(ticks)):
x1 = ticks[(i - 1)][1]
x2 = ticks[i][1]
dx = ((x2 - x1) / 10.0)
for j in range(1, 10):
x = (x1 + (dx * j))
stops.append((x, self.getColor(x)))
stops.append((x2, self.getColor(x2)))
g.setStops(stops)
return g
|
'Return a color for a given value.
**Arguments:**
x Value (position on gradient) of requested color.
toQColor If true, returns a QColor object, else returns a (r,g,b,a) tuple.'
| def getColor(self, x, toQColor=True):
| ticks = self.listTicks()
if (x <= ticks[0][1]):
c = ticks[0][0].color
if toQColor:
return QtGui.QColor(c)
else:
return (c.red(), c.green(), c.blue(), c.alpha())
if (x >= ticks[(-1)][1]):
c = ticks[(-1)][0].color
if toQColor:
return QtGui.QColor(c)
else:
return (c.red(), c.green(), c.blue(), c.alpha())
x2 = ticks[0][1]
for i in range(1, len(ticks)):
x1 = x2
x2 = ticks[i][1]
if ((x1 <= x) and (x2 >= x)):
break
dx = (x2 - x1)
if (dx == 0):
f = 0.0
else:
f = ((x - x1) / dx)
c1 = ticks[(i - 1)][0].color
c2 = ticks[i][0].color
if (self.colorMode == 'rgb'):
r = ((c1.red() * (1.0 - f)) + (c2.red() * f))
g = ((c1.green() * (1.0 - f)) + (c2.green() * f))
b = ((c1.blue() * (1.0 - f)) + (c2.blue() * f))
a = ((c1.alpha() * (1.0 - f)) + (c2.alpha() * f))
if toQColor:
return QtGui.QColor(int(r), int(g), int(b), int(a))
else:
return (r, g, b, a)
elif (self.colorMode == 'hsv'):
(h1, s1, v1, _) = c1.getHsv()
(h2, s2, v2, _) = c2.getHsv()
h = ((h1 * (1.0 - f)) + (h2 * f))
s = ((s1 * (1.0 - f)) + (s2 * f))
v = ((v1 * (1.0 - f)) + (v2 * f))
c = QtGui.QColor()
c.setHsv(h, s, v)
if toQColor:
return c
else:
return (c.red(), c.green(), c.blue(), c.alpha())
|
'Return an RGB(A) lookup table (ndarray).
**Arguments:**
nPts The number of points in the returned lookup table.
alpha True, False, or None - Specifies whether or not alpha values are included
in the table.If alpha is None, alpha will be automatically determined.'
| def getLookupTable(self, nPts, alpha=None):
| if (alpha is None):
alpha = self.usesAlpha()
if alpha:
table = np.empty((nPts, 4), dtype=np.ubyte)
else:
table = np.empty((nPts, 3), dtype=np.ubyte)
for i in range(nPts):
x = (float(i) / (nPts - 1))
color = self.getColor(x, toQColor=False)
table[i] = color[:table.shape[1]]
return table
|
'Return True if any ticks have an alpha < 255'
| def usesAlpha(self):
| ticks = self.listTicks()
for t in ticks:
if (t[0].color.alpha() < 255):
return True
return False
|
'Return True if the gradient has exactly two stops in it: black at 0.0 and white at 1.0'
| def isLookupTrivial(self):
| ticks = self.listTicks()
if (len(ticks) != 2):
return False
if ((ticks[0][1] != 0.0) or (ticks[1][1] != 1.0)):
return False
c1 = fn.colorTuple(ticks[0][0].color)
c2 = fn.colorTuple(ticks[1][0].color)
if ((c1 != (0, 0, 0, 255)) or (c2 != (255, 255, 255, 255))):
return False
return True
|
'Add a tick to the gradient. Return the tick.
**Arguments:**
x Position where tick should be added.
color Color of added tick. If color is not specified, the color will be
the color of the gradient at the specified position.
movable Specifies whether the tick is movable with the mouse.'
| def addTick(self, x, color=None, movable=True, finish=True):
| if (color is None):
color = self.getColor(x)
t = TickSliderItem.addTick(self, x, color=color, movable=movable)
t.colorChangeAllowed = True
t.removeAllowed = True
if finish:
self.sigGradientChangeFinished.emit(self)
return t
|
'Return a dictionary with parameters for rebuilding the gradient. Keys will include:
- \'mode\': hsv or rgb
- \'ticks\': a list of tuples (pos, (r,g,b,a))'
| def saveState(self):
| ticks = []
for t in self.ticks:
c = t.color
ticks.append((self.ticks[t], (c.red(), c.green(), c.blue(), c.alpha())))
state = {'mode': self.colorMode, 'ticks': ticks}
return state
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.