def test_PlotCurveItem():
p = pg.GraphicsWindow()
p.ci.layout.setContentsMargins(4, 4, 4, 4) # default margins vary by platform
v = p.addViewBox()
p.resize(200, 150)
data = np.array([1,4,2,3,np.inf,5,7,6,-np.inf,8,10,9,np.nan,-1,-2,0])
c = pg.PlotCurveItem(data)
v.addItem(c)
v.autoRange()
# Check auto-range works. Some platform differences may be expected..
checkRange = np.array([[-1.1457564053237301, 16.145756405323731], [-3.076811473165955, 11.076811473165955]])
assert np.allclose(v.viewRange(), checkRange)
assertImageApproved(p, 'plotcurveitem/connectall', "Plot curve with all points connected.")
c.setData(data, connect='pairs')
assertImageApproved(p, 'plotcurveitem/connectpairs', "Plot curve with pairs connected.")
c.setData(data, connect='finite')
assertImageApproved(p, 'plotcurveitem/connectfinite', "Plot curve with finite points connected.")
c.setData(data, connect=np.array([1,1,1,0,1,1,0,0,1,0,0,0,1,1,0,0]))
assertImageApproved(p, 'plotcurveitem/connectarray', "Plot curve with connection array.")
python类PlotCurveItem()的实例源码
def addCurve(self,plot,name='',**kwargs):
"""
Add a new curve to a 2D plot
.. tabularcolumns:: |p{3cm}|p{11cm}|
=============== ============================================================================================
**Arguments**
=============== ============================================================================================
plot QPlotWidget created using :func:`add2DPlot`
name something to call this trace. Shown in the legend too
=============== ============================================================================================
:return: pyqtgraph.PlotDataItem
"""
#if(len(name)):curve = pg.PlotDataItem(name=name)
curve = pg.PlotCurveItem(name = name,**kwargs)
plot.addItem(curve)
if self.properties['colorScheme']=='white':
curve.setPen(kwargs.get('pen',{'color':self.white_trace_colors[len(self.plots2D[plot])],'width':1}))
elif self.properties['colorScheme']=='black':
curve.setPen(kwargs.get('pen',{'color':self.black_trace_colors[len(self.plots2D[plot])],'width':1}))
#print (self.black_trace_colors[len(self.plots2D[plot])] , len(self.plots2D[plot]) )
self.plots2D[plot].append(curve)
return curve
def clear_graph(self):
# reset caching. if not, it is not cleared when view changing when zoomed
self.highlighted = None
self.curves_cont.setCacheMode(QGraphicsItem.NoCache)
self.curves_cont.setCacheMode(QGraphicsItem.DeviceCoordinateCache)
self.plot.vb.disableAutoRange()
self.curves_cont.clear()
self.curves_cont.update()
self.plotview.clear()
self.multiple_curves_info = []
self.curves_plotted = [] # currently plotted elements (for rescale)
self.curves = [] # for finding closest curve
self.plotview.addItem(self.label, ignoreBounds=True)
self.highlighted_curve = pg.PlotCurveItem(pen=self.pen_mouse)
self.highlighted_curve.setZValue(10)
self.highlighted_curve.hide()
self.plot.addItem(self.highlighted_curve)
self.plot.addItem(self.vLine, ignoreBounds=True)
self.plot.addItem(self.hLine, ignoreBounds=True)
self.viewhelpers = True
self.plot.addItem(self.curves_cont)
for m in self.markings:
self.plot.addItem(m, ignoreBounds=True)
def add_curves(self, x, ys, addc=True):
""" Add multiple curves with the same x domain. """
if len(ys) > MAX_INSTANCES_DRAWN:
sample_selection = random.Random(self.sample_seed).sample(range(len(ys)), MAX_INSTANCES_DRAWN)
# with random selection also show at most MAX_INSTANCES_DRAW elements from the subset
subset = set(np.where(self.subset_indices)[0])
subset_to_show = subset - set(sample_selection)
subset_additional = MAX_INSTANCES_DRAWN - (len(subset) - len(subset_to_show))
if len(subset_to_show) > subset_additional:
subset_to_show = random.Random(self.sample_seed).sample(subset_to_show, subset_additional)
self.sampled_indices = sorted(sample_selection + list(subset_to_show))
self.sampling = True
else:
self.sampled_indices = list(range(len(ys)))
random.Random(self.sample_seed).shuffle(self.sampled_indices) # for sequential classes#
self.sampled_indices_inverse = {s: i for i, s in enumerate(self.sampled_indices)}
ys = self.data.X[self.sampled_indices][:, self.data_xsind]
self.curves.append((x, ys))
for y in ys:
c = pg.PlotCurveItem(x=x, y=y, pen=self.pen_normal[None])
self.curves_cont.add_curve(c)
self.curves_plotted = self.curves
def test_PlotCurveItem():
p = pg.GraphicsWindow()
p.ci.layout.setContentsMargins(4, 4, 4, 4) # default margins vary by platform
v = p.addViewBox()
p.resize(200, 150)
data = np.array([1,4,2,3,np.inf,5,7,6,-np.inf,8,10,9,np.nan,-1,-2,0])
c = pg.PlotCurveItem(data)
v.addItem(c)
v.autoRange()
# Check auto-range works. Some platform differences may be expected..
checkRange = np.array([[-1.1457564053237301, 16.145756405323731], [-3.076811473165955, 11.076811473165955]])
assert np.allclose(v.viewRange(), checkRange)
assertImageApproved(p, 'plotcurveitem/connectall', "Plot curve with all points connected.")
c.setData(data, connect='pairs')
assertImageApproved(p, 'plotcurveitem/connectpairs', "Plot curve with pairs connected.")
c.setData(data, connect='finite')
assertImageApproved(p, 'plotcurveitem/connectfinite', "Plot curve with finite points connected.")
c.setData(data, connect=np.array([1,1,1,0,1,1,0,0,1,0,0,0,1,1,0,0]))
assertImageApproved(p, 'plotcurveitem/connectarray', "Plot curve with connection array.")
def plot_regression_line(self, x_data, y_data):
if self.plot_item:
self.plotview.removeItem(self.plot_item)
self.plot_item = pg.PlotCurveItem(
x=x_data, y=y_data,
pen=pg.mkPen(QColor(255, 0, 0), width=3),
antialias=True
)
self.plotview.addItem(self.plot_item)
self.plotview.replot()
def plot_error_bars(self, x, actual, predicted):
self.remove_error_items()
if self.error_bars_enabled:
for x, a, p in zip(x, actual, predicted):
line = pg.PlotCurveItem(
x=[x, x], y=[a, p],
pen=pg.mkPen(QColor(150, 150, 150), width=1),
antialias=True)
self.plotview.addItem(line)
self.error_plot_items.append(line)
self.plotview.replot()
def setup(self):
#self.ui = self.splitter = QtWidgets.QSplitter()
#self.ui.setLayout(QtWidgets.QVBoxLayout())
self.ui = self.dockarea = dockarea.DockArea()
self.imview = pg.ImageView()
self.imview.getView().invertY(False) # lower left origin
#self.splitter.addWidget(self.imview)
self.dockarea.addDock(name='Image', widget=self.imview)
self.graph_layout = pg.GraphicsLayoutWidget()
#self.splitter.addWidget(self.graph_layout)
self.dockarea.addDock(name='Spec Plot', widget=self.graph_layout)
self.spec_plot = self.graph_layout.addPlot()
self.rect_plotdata = self.spec_plot.plot()
self.point_plotdata = self.spec_plot.plot(pen=(0,9))
# Rectangle ROI
self.rect_roi = pg.RectROI([20, 20], [20, 20], pen=(0,9))
self.rect_roi.addTranslateHandle((0.5,0.5))
self.imview.getView().addItem(self.rect_roi)
self.rect_roi.sigRegionChanged[object].connect(self.on_change_rect_roi)
# Point ROI
self.circ_roi = pg.CircleROI( (0,0), (2,2) , movable=True, pen=(0,9))
#self.circ_roi.removeHandle(self.circ_roi.getHandles()[0])
h = self.circ_roi.addTranslateHandle((0.5,.5))
h.pen = pg.mkPen('r')
h.update()
self.imview.getView().addItem(self.circ_roi)
self.circ_roi.removeHandle(0)
self.circ_roi_plotline = pg.PlotCurveItem([0], pen=(0,9))
self.imview.getView().addItem(self.circ_roi_plotline)
self.circ_roi.sigRegionChanged[object].connect(self.on_update_circ_roi)
self.hyperspec_data = None
self.display_image = None
self.spec_x_array = None
self.scan_specific_setup()
def test_PlotCurvesItem_bounds(self):
pc = PlotCurvesItem()
# test defaults
np.testing.assert_equal(pc.boundingRect(), QRectF(0, 0, 1, 1))
pc.add_curve(pg.PlotCurveItem(x=[0, 1], y=[NAN, NAN]))
np.testing.assert_equal(pc.boundingRect(), QRectF(0, 0, 1, 1))
pc.add_curve(pg.PlotCurveItem(x=[-1, 2], y=[NAN, NAN]))
np.testing.assert_equal(pc.boundingRect(), QRectF(-1, 0, 3, 1))
# valid y values should overwrite the defaults
pc.add_curve(pg.PlotCurveItem(x=[-1, 2], y=[0.1, 0.2]))
np.testing.assert_equal(pc.boundingRect(), QRectF(-1, 0.1, 3, 0.1))
def __init__(self, graph):
ViewBox.__init__(self, enableMenu=False)
self.graph = graph
self.setMouseMode(self.PanMode)
self.zoomstartpoint = None
self.current_selection = None
self.action = PANNING
self.y_padding = 0.02
self.x_padding = 0
# line for marking selection
self.selection_line = pg.PlotCurveItem()
self.selection_line.setPen(pg.mkPen(color=QColor(Qt.black), width=2, style=Qt.DotLine))
self.selection_line.setZValue(1e9)
self.selection_line.hide()
self.addItem(self.selection_line, ignoreBounds=True)
# yellow marker for ending the polygon
self.selection_poly_marker = pg.ScatterPlotItem()
self.selection_poly_marker.setPen(pg.mkPen(color=QColor(Qt.yellow), width=2))
self.selection_poly_marker.setSize(SELECT_POLYGON_TOLERANCE*2)
self.selection_poly_marker.setBrush(None)
self.selection_poly_marker.setZValue(1e9+1)
self.selection_poly_marker.hide()
self.selection_poly_marker.mouseClickEvent = lambda x: x # ignore mouse clicks
self.addItem(self.selection_poly_marker, ignoreBounds=True)
def add_fill_curve(self, x, ylow, yhigh, pen):
phigh = pg.PlotCurveItem(x, yhigh, pen=pen)
plow = pg.PlotCurveItem(x, ylow, pen=pen)
color = pen.color()
color.setAlphaF(0.2)
cc = pg.mkBrush(color)
pfill = pg.FillBetweenItem(plow, phigh, brush=cc)
pfill.setZValue(10)
self.curves_cont.add_bounds(phigh)
self.curves_cont.add_bounds(plow)
self.curves_cont.add_curve(pfill, ignore_bounds=True)
# for zoom to work correctly
self.curves_plotted.append((x, np.array([ylow, yhigh])))
def __init__(self, parent=None,**kwargs):
super(AppWindow, self).__init__(parent)
self.setupUi(self)
self.I=kwargs.get('I',None)
self.I.set_gain('CH1',2)
self.I.set_gain('CH2',2)
self.setWindowTitle(self.I.H.version_string+' : '+params.get('name','').replace('\n',' ') )
self.plot1=self.add2DPlot(self.plot_area)
self.plot2=self.add2DPlot(self.plot_area)
self.legend = self.plot1.addLegend(offset=(-10,30))
self.curve1 = self.addCurve(self.plot1,'INPUT (CH1)')
self.curve2 = self.addCurve(self.plot1,'OUTPUT(CH2)')
self.p2=self.enableRightAxis(self.plot2)
self.plot2.getAxis('right').setLabel('Phase', color='#00ffff')
self.plot2.getAxis('left').setLabel('Amplitude', color='#ffffff')
self.plot1.getAxis('bottom').setLabel('Time',units='S' ,color='#ffffff')
self.plot2.getAxis('bottom').setLabel('Frequency',units='Hz', color='#ffffff')
self.p2.setYRange(-360,360)
self.curvePhase=self.addCurve(self.p2,'PHASE',pen=[0,255,255])#pg.PlotCurveItem()
self.curveAmp = self.addCurve(self.plot2,'AMPLITUDE',pen=[255,255,255])
self.totalpoints=2000
self.samples = 2000
self.X=[]
self.Y=[]
self.curves=[]
self.curveLabels=[]
from PSL.analyticsClass import analyticsClass
self.CC = analyticsClass()
self.I.configure_trigger(0,'CH1',0)
self.I.set_sine1(5000)
self.I.__autoRangeScope__(2)
self.I.set_sine1(2)
self.freqs=[]
self.amps=[]
self.dP=[]
self.STARTFRQ=self.startFreq.value()
self.ENDFRQ=self.stopFreq.value()
self.STEPFRQ=self.stepFreq.value()
self.loop=None
self.plot2.setXRange(self.STARTFRQ,self.ENDFRQ)
self.plot2.setYRange(0,1.)
self.plot1.setLimits(xMin = 0,yMin=-8,yMax=8)
self.running = False
def __init__(self, parent=None,**kwargs):
super(AppWindow, self).__init__(parent)
self.setupUi(self)
self.I=kwargs.get('I',None)
self.I.set_gain('CH1',2)
self.I.set_gain('CH2',2)
self.setWindowTitle(self.I.H.version_string+' : '+params.get('name','').replace('\n',' ') )
self.plot1=self.add2DPlot(self.plot_area)
self.plot2=self.add2DPlot(self.plot_area)
#self.enableCrossHairs(self.plot2,[])
self.legend = self.plot1.addLegend(offset=(-10,30))
self.curve1 = self.addCurve(self.plot1,'INPUT (CH1)')
self.curve2 = self.addCurve(self.plot1,'OUTPUT(CH2)')
self.p2=self.enableRightAxis(self.plot2)
self.plot2.getAxis('right').setLabel('Phase', color='#00ffff')
self.plot2.getAxis('left').setLabel('Amplitude', color='#ffffff')
self.plot1.getAxis('bottom').setLabel('Time',units='S' ,color='#ffffff')
self.plot2.getAxis('bottom').setLabel('Frequency',units='Hz', color='#ffffff')
self.p2.setYRange(-360,360)
self.curvePhase=self.addCurve(self.p2,'PHASE',pen=[0,255,255])#pg.PlotCurveItem()
self.curveAmp = self.addCurve(self.plot2,'AMPLITUDE',pen=[255,255,255])
#self.ControlsLayout.addWidget(self.gainIconCombined(FUNC=self.I.set_gain,LINK=self.autoRange))
self.pv = self.addPV3(self.I)
self.ControlsLayout.addWidget(self.pv)
self.pv.dial.setValue(2048)
self.totalpoints=2000
self.samples = 2000
self.X=[]
self.Y=[]
self.curves=[]
self.curveLabels=[]
from PSL.analyticsClass import analyticsClass
self.CC = analyticsClass()
self.I.configure_trigger(0,'CH1',0)
self.I.set_sine1(5000)
self.I.__autoRangeScope__(2)
self.I.set_sine1(2)
self.freqs=[]
self.amps=[]
self.dP=[]
self.STARTFRQ=self.startFreq.value()
self.ENDFRQ=self.stopFreq.value()
self.STEPFRQ=self.stepFreq.value()
self.loop=None
self.plot2.setXRange(self.STARTFRQ,self.ENDFRQ)
self.plot2.setYRange(0,1.)
self.plot1.setLimits(xMin = 0,yMin=-8,yMax=8)
self.running = False
def refresh_integral_markings(dis, markings_list, curveplot):
for m in markings_list:
if m in curveplot.markings:
curveplot.remove_marking(m)
markings_list.clear()
def add_marking(a):
markings_list.append(a)
curveplot.add_marking(a)
for di in dis:
if di is None:
continue # nothing to draw
color = QColor(di.get("color", "red"))
for el in di["draw"]:
if el[0] == "curve":
bs_x, bs_ys, penargs = el[1]
curve = pg.PlotCurveItem()
curve.setPen(pg.mkPen(color=QColor(color), **penargs))
curve.setZValue(10)
curve.setData(x=bs_x, y=bs_ys[0])
add_marking(curve)
elif el[0] == "fill":
(x1, ys1), (x2, ys2) = el[1]
phigh = pg.PlotCurveItem(x1, ys1[0], pen=None)
plow = pg.PlotCurveItem(x2, ys2[0], pen=None)
color = QColor(color)
color.setAlphaF(0.5)
cc = pg.mkBrush(color)
pfill = pg.FillBetweenItem(plow, phigh, brush=cc)
pfill.setZValue(9)
add_marking(pfill)
elif el[0] == "line":
(x1, y1), (x2, y2) = el[1]
line = pg.PlotCurveItem()
line.setPen(pg.mkPen(color=QColor(color), width=4))
line.setZValue(10)
line.setData(x=[x1[0], x2[0]], y=[y1[0], y2[0]])
add_marking(line)
elif el[0] == "dot":
(x, ys) = el[1]
dot = pg.ScatterPlotItem(x=x, y=ys[0])
dot.setPen(pg.mkPen(color=QColor(color), width=5))
dot.setZValue(10)
add_marking(dot)