Python pyqtgraph 模块,mkPen() 实例源码

我们从Python开源项目中,提取了以下41个代码示例,用于说明如何使用pyqtgraph.mkPen()

项目:pyrpl    作者:lneuhaus    | 项目源码 | 文件源码
def init_gui(self):
        #self.main_layout = QtWidgets.QVBoxLayout(self)
        self.init_main_layout(orientation="vertical")
        self.init_attribute_layout()

        self.win = pg.GraphicsWindow(title="Expected signal")
        self.plot_item = self.win.addPlot(title='Expected ' + self.module.name)
        self.plot_item.showGrid(y=True, x=True, alpha=1.)
        self.curve = self.plot_item.plot(pen='y')
        self.curve_slope = self.plot_item.plot(pen=pg.mkPen('b', width=5))
        self.symbol = self.plot_item.plot(pen='b', symbol='o')
        self.main_layout.addWidget(self.win)
        self.button_calibrate = QtWidgets.QPushButton('Calibrate')
        self.main_layout.addWidget(self.button_calibrate)
        self.button_calibrate.clicked.connect(lambda: self.module.calibrate())
        self.input_calibrated()
项目:qudi    作者:Ulm-IQO    | 项目源码 | 文件源码
def fit_clicked(self):
        """ Do the configured fit and show it in the sum plot """
        self._mw.fit_param_TextEdit.clear()

        current_fit_function = self._mw.fit_methods_ComboBox.currentText()

        fit_x, fit_y, fit_param_dict, fit_result = self._trace_analysis.do_fit(fit_function=current_fit_function)

        self._fit_image.setData(x=fit_x, y=fit_y, pen=pg.mkPen(palette.c2, width=2))

        if len(fit_param_dict) == 0:
            fit_result = 'No Fit parameter passed.'

        else:
            fit_result = units.create_formatted_output(fit_param_dict)
        self._mw.fit_param_TextEdit.setPlainText(fit_result)

        return
项目:Python-GUI-examples    作者:swharden    | 项目源码 | 文件源码
def update(self):
        if not self.ear.data is None and not self.ear.fft is None:
            pcmMax=np.max(np.abs(self.ear.data))
            if pcmMax>self.maxPCM:
                self.maxPCM=pcmMax
                self.grPCM.plotItem.setRange(yRange=[-pcmMax,pcmMax])
            if np.max(self.ear.fft)>self.maxFFT:
                self.maxFFT=np.max(np.abs(self.ear.fft))
                #self.grFFT.plotItem.setRange(yRange=[0,self.maxFFT])
                self.grFFT.plotItem.setRange(yRange=[0,1])
            self.pbLevel.setValue(1000*pcmMax/self.maxPCM)
            pen=pyqtgraph.mkPen(color='b')
            self.grPCM.plot(self.ear.datax,self.ear.data,pen=pen,clear=True)
            pen=pyqtgraph.mkPen(color='r')
            self.grFFT.plot(self.ear.fftx,self.ear.fft/self.maxFFT,pen=pen,clear=True)
        QtCore.QTimer.singleShot(1, self.update) # QUICKLY repeat
项目:kite    作者:pyrocko    | 项目源码 | 文件源码
def addPlot(self, plot):
        image = plot.image
        if not self.plots:
            self.setImageItem(image)

        self.plots.append(plot)
        self.setSymColormap()

        # hist_pen = pg.mkPen((170, 57, 57, 255), width=1.)
        image.setLookupTable(self.getLookupTable)

        def updateLevels():
            image.setLevels(self.region.getRegion())

        self.sigLevelChangeFinished.connect(updateLevels)
        self.sigLevelsChanged.connect(updateLevels)
        updateLevels()
项目:picosdk-python-examples    作者:picotech    | 项目源码 | 文件源码
def triggerKnobEnabledChange(self, state):
        self.triggerKnobSource.setEnabled(state)
        self.triggerKnobDirection.setEnabled(state)
        if state:
            if self.triggX is None:
                self.triggX = 0.5
            if self.triggY is None:
                self.triggY = 0
            if self.triggerDiamond is None:
                self.triggerDiamond = pg.RectROI([self.triggX * self.samples / self.ratioBin, self.triggY],
                                                 [0, 0], invertible=True, pen=pg.mkPen(None))
                self.triggerDiamond.sigRegionChanged.connect(self.triggerDiamondUpdate)
                self.viewPlot.addItem(self.triggerDiamond)
        else:
            self.viewPlot.removeItem(self.triggerDiamond)
            self.triggerDiamond = None
        self.triggerReset = True
项目:orange-infrared    作者:markotoplak    | 项目源码 | 文件源码
def set_pen_colors(self):
        self.pen_normal.clear()
        self.pen_subset.clear()
        self.pen_selected.clear()
        color_var = self._current_color_var()
        if color_var is not None:
            colors = color_var.colors
            discrete_palette = ColorPaletteGenerator(
                number_of_colors=len(colors), rgb_colors=colors)
            for v in color_var.values:
                basecolor = discrete_palette[color_var.to_val(v)]
                basecolor = QColor(basecolor)
                basecolor.setAlphaF(0.9)
                self.pen_subset[v] = pg.mkPen(color=basecolor, width=1)
                self.pen_selected[v] = pg.mkPen(color=basecolor, width=2, style=Qt.DotLine)
                notselcolor = basecolor.lighter(150)
                notselcolor.setAlphaF(0.5)
                self.pen_normal[v] = pg.mkPen(color=notselcolor, width=1)
项目:diyECG-1opAmp    作者:swharden    | 项目源码 | 文件源码
def update(self):
        t1,timeTook=time.time(),0
        if len(self.ear.data) and not self.btnPause.isChecked():
            freqHighCutoff=0
            if self.spinLowpass.value()>0:
                freqHighCutoff=self.spinLowpass.value()
            data=self.ear.getFiltered(freqHighCutoff)
            if self.chkInvert.isChecked():
                data=np.negative(data)
            if self.chkAutoscale.isChecked():
                self.Yscale=np.max(np.abs(data))*1.1
            self.grECG.plotItem.setRange(xRange=[0,self.ear.maxMemorySec],
                            yRange=[-self.Yscale,self.Yscale],padding=0)
            self.grECG.plot(np.arange(len(data))/float(self.ear.rate),data,clear=True,
                            pen=pyqtgraph.mkPen(color='r'),antialias=True)
            self.grECG.plotItem.setTitle(self.lineTitle.text(),color=(0,0,0))
            self.stamp.setPos(0,-self.Yscale)
            self.grECG.plotItem.addItem(self.stamp)
            timeTook=(time.time()-t1)*1000
            print("plotting took %.02f ms"%(timeTook))
        msTillUpdate=int(self.ear.chunk/self.ear.rate*1000)-timeTook
        QtCore.QTimer.singleShot(max(0,msTillUpdate), self.update)
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
def test_init_spots():
    plot = pg.PlotWidget()
    # set view range equal to its bounding rect. 
    # This causes plots to look the same regardless of pxMode.
    plot.setRange(rect=plot.boundingRect())
    spots = [
        {'x': 0, 'y': 1},
        {'pos': (1, 2), 'pen': None, 'brush': None, 'data': 'zzz'},
    ]
    s = pg.ScatterPlotItem(spots=spots)

    # Check we can display without errors
    plot.addItem(s)
    app.processEvents()
    plot.clear()

    # check data is correct
    spots = s.points()

    defPen = pg.mkPen(pg.getConfigOption('foreground'))

    assert spots[0].pos().x() == 0
    assert spots[0].pos().y() == 1
    assert spots[0].pen() == defPen
    assert spots[0].data() is None

    assert spots[1].pos().x() == 1
    assert spots[1].pos().y() == 2
    assert spots[1].pen() == pg.mkPen(None)
    assert spots[1].brush() == pg.mkBrush(None)
    assert spots[1].data() == 'zzz'
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
def test_init_spots():
    plot = pg.PlotWidget()
    # set view range equal to its bounding rect. 
    # This causes plots to look the same regardless of pxMode.
    plot.setRange(rect=plot.boundingRect())
    spots = [
        {'x': 0, 'y': 1},
        {'pos': (1, 2), 'pen': None, 'brush': None, 'data': 'zzz'},
    ]
    s = pg.ScatterPlotItem(spots=spots)

    # Check we can display without errors
    plot.addItem(s)
    app.processEvents()
    plot.clear()

    # check data is correct
    spots = s.points()

    defPen = pg.mkPen(pg.getConfigOption('foreground'))

    assert spots[0].pos().x() == 0
    assert spots[0].pos().y() == 1
    assert spots[0].pen() == defPen
    assert spots[0].data() is None

    assert spots[1].pos().x() == 1
    assert spots[1].pos().y() == 2
    assert spots[1].pen() == pg.mkPen(None)
    assert spots[1].brush() == pg.mkBrush(None)
    assert spots[1].data() == 'zzz'
项目:InplusTrader_Linux    作者:zhengwsh    | 项目源码 | 文件源码
def generatePicture(self):
            ## pre-computing a QPicture object allows paint() to run much more quickly,
            ## rather than re-drawing the shapes every time.
            self.picture = QtGui.QPicture()
            p = QtGui.QPainter(self.picture)
            p.setPen(pg.mkPen(color='r', width=0.4))  # 0.4 means w*2
            # w = (self.data[1][0] - self.data[0][0]) / 3.
            w = 0.2
            for (t, open, close, min, max) in self.data:
                p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
                if open > close:
                    p.setBrush(pg.mkBrush('g'))
                else:
                    p.setBrush(pg.mkBrush('r'))
                p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open))
            p.end()
项目:InplusTrader_Linux    作者:zhengwsh    | 项目源码 | 文件源码
def generatePicture(self):
        ## pre-computing a QPicture object allows paint() to run much more quickly,
        ## rather than re-drawing the shapes every time.
        self.picture = QtGui.QPicture()
        p = QtGui.QPainter(self.picture)
        p.setPen(pg.mkPen(color='r', width=0.4))  # 0.4 means w*2
        # w = (self.data[1][0] - self.data[0][0]) / 3.
        w = 0.2
        for (t, open, close, min, max) in self.data:
            p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
            if open > close:
                p.setBrush(pg.mkBrush('g'))
            else:
                p.setBrush(pg.mkBrush('r'))
            p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open))
        p.end()
项目:orange3-educational    作者:biolab    | 项目源码 | 文件源码
def plot_scatter_points(self, x_data, y_data):
        if self.scatterplot_item:
            self.plotview.removeItem(self.scatterplot_item)
        self.n_points = len(x_data)
        self.scatterplot_item = pg.ScatterPlotItem(
            x=x_data, y=y_data, data=np.arange(self.n_points),
            symbol="o", size=10, pen=pg.mkPen(0.2), brush=pg.mkBrush(0.7),
            antialias=True)
        self.scatterplot_item.opts["useCache"] = False
        self.plotview.addItem(self.scatterplot_item)
        self.plotview.replot()
项目:orange3-educational    作者:biolab    | 项目源码 | 文件源码
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()
项目:orange3-educational    作者:biolab    | 项目源码 | 文件源码
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()
项目:qudi    作者:Ulm-IQO    | 项目源码 | 文件源码
def refresh_colorbar(self, cb_min, cb_max, width = None, height = None, xMin = None, yMin = None):
        """ Refresh the appearance of the colorbar for a changed count range.

        @param float cb_min: The minimal count value should be passed here.
        @param float cb_max: The maximal count value should be passed here.
        @param float width: optional, with that you can change the width of the
                            colorbar in the display.
        """

        if width is None:
            width = self.width
        else:
            self.width = width

#       FIXME: Until now, if you want to refresh the colorbar, a new QPainter
#              object has been created, but I think that it is not necassary.
#              I have to figure out how to use the created object properly.
        p = pg.QtGui.QPainter(self.pic)
        p.drawRect(self.boundingRect())
        p.setPen(pg.mkPen('k'))
        grad = pg.QtGui.QLinearGradient(width/2.0, cb_min*1.0, width/2.0, cb_max*1.0)
        for stop, color in zip(self.stops, self.colors):
            grad.setColorAt(1.0 - stop, pg.QtGui.QColor(*[255*c for c in color]))
        p.setBrush(pg.QtGui.QBrush(grad))
        if xMin is None:
            p.drawRect(pg.QtCore.QRectF(0, cb_min, width, cb_max-cb_min))
        else:
            # If this picture whants to be set in a plot, which is going to be
            # saved:
            p.drawRect(pg.QtCore.QRectF(xMin, yMin, width, height))
        p.end()

        vb = self.getViewBox()
        # check whether a viewbox is already created for this object. If yes,
        # then it should be adjusted according to the full screen.
        if vb is not None:
            vb.updateAutoRange()
            vb.enableAutoRange()
项目:pyinduct    作者:pyinduct    | 项目源码 | 文件源码
def test_lag1st_to_trig(self):
        # scalar case
        dest_weight = core.change_projection_base(self.src_weights, self.src_test_funcs, self.trig_test_funcs[0])
        dest_approx_handle_s = core.back_project_from_base(dest_weight, self.trig_test_funcs[0])

        # standard case
        dest_weights = core.change_projection_base(self.src_weights, self.src_test_funcs, self.trig_test_funcs)
        dest_approx_handle = core.back_project_from_base(dest_weights, self.trig_test_funcs)
        error = np.sum(np.power(
            np.subtract(self.real_func_handle(self.z_values), dest_approx_handle(self.z_values)),
            2))

        if show_plots:
            pw = pg.plot(title="change projection base")
            i1 = pw.plot(x=self.z_values, y=self.real_func_handle(self.z_values), pen="r")
            i2 = pw.plot(x=self.z_values, y=self.src_approx_handle(self.z_values),
                         pen=pg.mkPen("g", style=pg.QtCore.Qt.DashLine))
            i3 = pw.plot(x=self.z_values, y=dest_approx_handle_s(self.z_values), pen="b")
            i4 = pw.plot(x=self.z_values, y=dest_approx_handle(self.z_values), pen="c")
            legend = pw.addLegend()
            legend.addItem(i1, "f(x) = x")
            legend.addItem(i2, "2x Lagrange1st")
            legend.addItem(i3, "sin(x)")
            legend.addItem(i4, "sin(wx) with w in [1, {0}]".format(dest_weights.shape[0]))
            app.exec_()

        # should fit pretty nice
        self.assertLess(error, 1e-2)
项目:pyinduct    作者:pyinduct    | 项目源码 | 文件源码
def __init__(self, t, u, show_plot=False):
        SimulationInput.__init__(self)

        self._t = t
        self._T = t[-1]
        self._u = u
        self.scale = 1

        if show_plot:
            pw = pg.plot(title="InterpTrajectory")
            pw.plot(self._t, self.__call__(time=self._t))
            pw.plot([0, self._T], self.__call__(time=[0, self._T]), pen=None, symbolPen=pg.mkPen("g"))
            pg.QtGui.QApplication.instance().exec_()
项目:Python-GUI-examples    作者:swharden    | 项目源码 | 文件源码
def update(self):
        t1=time.clock()
        points=100 #number of data points
        X=np.arange(points)
        Y=np.sin(np.arange(points)/points*3*np.pi+time.time())
        C=pyqtgraph.hsvColor(time.time()/5%1,alpha=.5)
        pen=pyqtgraph.mkPen(color=C,width=10)
        self.grPlot.plot(X,Y,pen=pen,clear=True)
        print("update took %.02f ms"%((time.clock()-t1)*1000))
        if self.chkMore.isChecked():
            QtCore.QTimer.singleShot(1, self.update) # QUICKLY repeat
项目:kite    作者:pyrocko    | 项目源码 | 文件源码
def addPolyLine(self):
        [[xmin, xmax], [ymin, ymax]] = self.plot.viewRange()
        self.poly_line = pg.PolyLineROI(
            positions=[(xmin+(xmax-xmin)*.4,
                        ymin+(ymax-ymin)*.4),
                       (xmin+(xmax-xmin)*.6,
                        ymin+(ymax-ymin)*.6)],
            pen=pg.mkPen('g', width=2))
        self.plot.addItem(self.poly_line)
        self.updateTransPlot()

        self.poly_line.sigRegionChangeFinished.connect(
            self.updateTransPlot)
项目:kite    作者:pyrocko    | 项目源码 | 文件源码
def setGradientEditor(self, gradient_editor):
            ge = gradient_editor
            image = self.image

            hist_pen = pg.mkPen((170, 57, 57, 255), width=1.)
            image.setLookupTable(ge.getLookupTable)

            def updateLevels():
                image.setLevels(ge.region.getRegion())

            ge.sigLevelChangeFinished.connect(updateLevels)
            ge.sigLevelsChanged.connect(updateLevels)
            updateLevels()

            def updateHistogram():
                h = image.getHistogram()
                if h[0] is None:
                    return
                ge.hist_syn.setData(*h)

            ge.hist_syn = pg.PlotDataItem(pen=hist_pen)
            ge.hist_syn.rotate(90.)
            ge.vb.addItem(ge.hist_syn)
            updateHistogram()

            image.sigImageChanged.connect(updateHistogram)
项目:specviz    作者:spacetelescope    | 项目源码 | 文件源码
def pen(self, pen):
        if isinstance(pen, QColor):
            pen = pg.mkPen(pen)

        _inactive_pen = pg.mkPen(QColor(pen.color().red(),
                                        pen.color().green(),
                                        pen.color().blue(),
                                        50))

        if self._plot.opts['pen'] == self._pen_stash['pen_on']:
            self._pen_stash['pen_on'] = pg.mkPen(pen, width=self.line_width)
            self._plot.setPen(self._pen_stash['pen_on'])
        elif self._plot.opts['pen'] == self._pen_stash['pen_inactive']:
            self._pen_stash['pen_inactive'] = _inactive_pen
            self._plot.setPen(self._pen_stash['pen_inactive'])
项目:specviz    作者:spacetelescope    | 项目源码 | 文件源码
def error_pen(self, pen):
        self._pen_stash['error_pen_on'] = pg.mkPen(pen)

        if self.error is not None:
            self.error.setOpts(pen=pg.mkPen(pen))
项目:specviz    作者:spacetelescope    | 项目源码 | 文件源码
def mask_pen(self, pen):
        self._pen_stash['mask_pen_on'] = pg.mkPen(pen)

        if self.error is not None:
            self.error.setPen(pen=pg.mkPen(pen))
项目:specviz    作者:spacetelescope    | 项目源码 | 文件源码
def set_line_width(self, width):
        """
        Set the line plot width

        Parameters
        ----------
        width: float
            The width of the line
        """
        self.line_width = width
        _pen = pg.mkPen(self._plot.opts['pen'])
        _pen.setWidth(self.line_width)
        self.pen = _pen
项目:ScopeFoundry    作者:ScopeFoundry    | 项目源码 | 文件源码
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()
项目:orange-infrared    作者:markotoplak    | 项目源码 | 文件源码
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)
项目:orange-infrared    作者:markotoplak    | 项目源码 | 文件源码
def __init__(self, position, label="", setvalfn=None, confirmfn=None,
                 color=(225, 0, 0), report=None):
        pg.UIGraphicsItem.__init__(self)
        self.moving = False
        self.mouseHovering = False
        self.report = report

        hp = pg.mkPen(color=color, width=3)
        np = pg.mkPen(color=color, width=2)
        self.line = pg.InfiniteLine(angle=90, movable=True, pen=np, hoverPen=hp)

        if position is not None:
            self.line.setValue(position)
        else:
            self.line.setValue(0)
            self.line.hide()
        self.line.setCursor(Qt.SizeHorCursor)

        self.line.setParentItem(self)
        self.line.sigPositionChangeFinished.connect(self.lineMoveFinished)
        self.line.sigPositionChanged.connect(self.lineMoved)

        self.label = pg.TextItem("", anchor=(0,0))
        self.label.setText(label, color=color)
        self.label.setParentItem(self)

        self.setvalfn = setvalfn
        self.confirmfn = confirmfn

        self.lastTransform = None
项目:uwb_tracker_ros    作者:eth-ait    | 项目源码 | 文件源码
def update_visualization(self, tofs, ranges, clock_offsets, clock_skews, slave_clock_offset, slave_clock_skew):
        if not self.show_plots:
            return

        import pyqtgraph
        num_of_units = len(tofs)

        # ranges
        while len(self.range_plot) < num_of_units:
            curve_index = len(self.range_plot)
            pen = pyqtgraph.mkPen(curve_index)
            self.range_plot.add_curve(pen=pen, name="{}".format(curve_index))
        for i in xrange(num_of_units):
            self.range_plot.add_point(i, ranges[i])

        # clock offset
        while len(self.clock_offset_plot) < num_of_units:
            curve_index = len(self.clock_offset_plot)
            pen = pyqtgraph.mkPen(curve_index)
            self.clock_offset_plot.add_curve(pen=pen, name="{}".format(curve_index))
        if self.show_slave_clock_offset:
            if len(self.clock_offset_plot) < num_of_units + 1:
                curve_index = len(self.clock_offset_plot)
                pen = pyqtgraph.mkPen(curve_index)
                self.clock_offset_plot.add_curve(pen=pen, name="slave")
        for i in xrange(num_of_units):
            self.clock_offset_plot.add_point(i, clock_offsets[i])
        if self.show_slave_clock_offset:
            self.clock_offset_plot.add_point(len(self.clock_offset_plot) - 1, slave_clock_offset)

        # clock skew
        while len(self.clock_skew_plot) < num_of_units:
            curve_index = len(self.clock_skew_plot)
            pen = pyqtgraph.mkPen(curve_index)
            self.clock_skew_plot.add_curve(pen=pen, name="{}".format(curve_index))
        if self.show_slave_clock_skew:
            if len(self.clock_skew_plot) < num_of_units + 1:
                curve_index = len(self.clock_skew_plot)
                pen = pyqtgraph.mkPen(curve_index)
                self.clock_skew_plot.add_curve(pen=pen, name="slave")
        for i in xrange(num_of_units):
            self.clock_skew_plot.add_point(i, clock_skews[i])
        if self.show_slave_clock_skew:
            self.clock_skew_plot.add_point(len(self.clock_skew_plot) - 1, slave_clock_skew)
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
def test_scatterplotitem():
    plot = pg.PlotWidget()
    # set view range equal to its bounding rect. 
    # This causes plots to look the same regardless of pxMode.
    plot.setRange(rect=plot.boundingRect())
    for i, pxMode in enumerate([True, False]):
        for j, useCache in enumerate([True, False]):
            s = pg.ScatterPlotItem()
            s.opts['useCache'] = useCache
            plot.addItem(s)
            s.setData(x=np.array([10,40,20,30])+i*100, y=np.array([40,60,10,30])+j*100, pxMode=pxMode)
            s.addPoints(x=np.array([60, 70])+i*100, y=np.array([60, 70])+j*100, size=[20, 30])

            # Test uniform spot updates
            s.setSize(10)
            s.setBrush('r')
            s.setPen('g')
            s.setSymbol('+')
            app.processEvents()

            # Test list spot updates
            s.setSize([10] * 6)
            s.setBrush([pg.mkBrush('r')] * 6)
            s.setPen([pg.mkPen('g')] * 6)
            s.setSymbol(['+'] * 6)
            s.setPointData([s] * 6)
            app.processEvents()

            # Test array spot updates
            s.setSize(np.array([10] * 6))
            s.setBrush(np.array([pg.mkBrush('r')] * 6))
            s.setPen(np.array([pg.mkPen('g')] * 6))
            s.setSymbol(np.array(['+'] * 6))
            s.setPointData(np.array([s] * 6))
            app.processEvents()

            # Test per-spot updates
            spot = s.points()[0]
            spot.setSize(20)
            spot.setBrush('b')
            spot.setPen('g')
            spot.setSymbol('o')
            spot.setData(None)
            app.processEvents()

    plot.clear()
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
def test_simple():
    tempfilename = tempfile.NamedTemporaryFile(suffix='.svg').name
    print("using %s as a temporary file" % tempfilename)
    scene = pg.QtGui.QGraphicsScene()
    #rect = pg.QtGui.QGraphicsRectItem(0, 0, 100, 100)
    #scene.addItem(rect)
    #rect.setPos(20,20)
    #rect.translate(50, 50)
    #rect.rotate(30)
    #rect.scale(0.5, 0.5)

    #rect1 = pg.QtGui.QGraphicsRectItem(0, 0, 100, 100)
    #rect1.setParentItem(rect)
    #rect1.setFlag(rect1.ItemIgnoresTransformations)
    #rect1.setPos(20, 20)
    #rect1.scale(2,2)

    #el1 = pg.QtGui.QGraphicsEllipseItem(0, 0, 100, 100)
    #el1.setParentItem(rect1)
    ##grp = pg.ItemGroup()
    #grp.setParentItem(rect)
    #grp.translate(200,0)
    ##grp.rotate(30)

    #rect2 = pg.QtGui.QGraphicsRectItem(0, 0, 100, 25)
    #rect2.setFlag(rect2.ItemClipsChildrenToShape)
    #rect2.setParentItem(grp)
    #rect2.setPos(0,25)
    #rect2.rotate(30)
    #el = pg.QtGui.QGraphicsEllipseItem(0, 0, 100, 50)
    #el.translate(10,-5)
    #el.scale(0.5,2)

    #el.setParentItem(rect2)

    grp2 = pg.ItemGroup()
    scene.addItem(grp2)
    grp2.scale(100,100)

    rect3 = pg.QtGui.QGraphicsRectItem(0,0,2,2)
    rect3.setPen(pg.mkPen(width=1, cosmetic=False))
    grp2.addItem(rect3)

    ex = pg.exporters.SVGExporter(scene)
    ex.export(fileName=tempfilename)
    os.unlink(tempfilename)
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
def test_scatterplotitem():
    plot = pg.PlotWidget()
    # set view range equal to its bounding rect. 
    # This causes plots to look the same regardless of pxMode.
    plot.setRange(rect=plot.boundingRect())
    for i, pxMode in enumerate([True, False]):
        for j, useCache in enumerate([True, False]):
            s = pg.ScatterPlotItem()
            s.opts['useCache'] = useCache
            plot.addItem(s)
            s.setData(x=np.array([10,40,20,30])+i*100, y=np.array([40,60,10,30])+j*100, pxMode=pxMode)
            s.addPoints(x=np.array([60, 70])+i*100, y=np.array([60, 70])+j*100, size=[20, 30])

            # Test uniform spot updates
            s.setSize(10)
            s.setBrush('r')
            s.setPen('g')
            s.setSymbol('+')
            app.processEvents()

            # Test list spot updates
            s.setSize([10] * 6)
            s.setBrush([pg.mkBrush('r')] * 6)
            s.setPen([pg.mkPen('g')] * 6)
            s.setSymbol(['+'] * 6)
            s.setPointData([s] * 6)
            app.processEvents()

            # Test array spot updates
            s.setSize(np.array([10] * 6))
            s.setBrush(np.array([pg.mkBrush('r')] * 6))
            s.setPen(np.array([pg.mkPen('g')] * 6))
            s.setSymbol(np.array(['+'] * 6))
            s.setPointData(np.array([s] * 6))
            app.processEvents()

            # Test per-spot updates
            spot = s.points()[0]
            spot.setSize(20)
            spot.setBrush('b')
            spot.setPen('g')
            spot.setSymbol('o')
            spot.setData(None)
            app.processEvents()

    plot.clear()
项目:pslab-desktop-apps    作者:fossasia    | 项目源码 | 文件源码
def __init__(self, parent=None,**kwargs):
        super(AppWindow, self).__init__(parent)
        self.setupUi(self)
        self.I=kwargs.get('I',None)
        self.INPUTS=['CH1','CH2','CH3']
        self.calibrateOnlyADC = True #DACs will have to calibrated against the ADCs later
        self.type1text = 'PV3->(AN8 or CAP, AIN7), PV2->CH1,2,3,AIN6 , PV1->AIN5'
        self.type2text = 'PV3->(AN8 or CAP, AIN7), PV1->(AIN6, CH1,CH2,CH3), '

        self.setType(0)
        self.A = acquirer(self)
        self.INLBox.setCurrentIndex(1)
        self.typeSelectBox.setCurrentIndex(1)
        self.hexid = hex(self.I.device_id())
        self.savedir = os.path.join('.',self.hexid)

        self.setWindowTitle(self.I.generic_name + ' : '+self.I.H.version_string.decode("utf-8")+' : '+self.hexid)

        for a in range(8):
            item = QtGui.QTableWidgetItem()
            self.valueTable.setItem(0,a,item)
            item.setText('.')

        self.plot=self.add2DPlot(self.plot_area)
        labelStyle = {'color': 'rgb(255,255,255)', 'font-size': '11pt'}
        self.plot.setLabel('left','Read Voltages -->', units='V',**labelStyle)
        self.plot.setLabel('bottom','Actual Voltage -->', units='V',**labelStyle)
        #self.plot.setYRange(-.1,.1)
        self.curves={}

        self.curves['INL']=self.addCurve(self.plot,pen=pg.mkPen([255,255,255], width=1),name='INL')
        item = self.addLabel('INL',[255,255,255]);  self.curves['INL'].curve.setClickable(True);    self.curves['INL'].sigClicked.connect(functools.partial(self.selectItem,item))

        self.curves['PV3']=self.addCurve(self.plot,pen=pg.mkPen([255,255,255], width=1),name='PV3')
        item = self.addLabel('PV3',[255,255,255]); self.curves['PV3'].curve.setClickable(True); self.curves['PV3'].sigClicked.connect(functools.partial(self.selectItem,item))


        for a in self.INPUTS:
            self.curves[a]={}
            if self.I.analogInputSources[a].gainEnabled:
                for b in range(8):
                    col=QtGui.QColor(random.randint(20,255),random.randint(20,255),random.randint(20,255))
                    name = '%s:%dx'%(a,self.I.gain_values[b])
                    self.curves[a][b]=self.addCurve(self.plot,pen=pg.mkPen(col, width=1),name=name)
                    item = self.addLabel(name,col); self.curves[a][b].curve.setClickable(True); self.curves[a][b].sigClicked.connect(functools.partial(self.selectItem,item))
            else:
                col=QtGui.QColor(random.randint(20,255),random.randint(20,255),random.randint(20,255))
                name = '%s:1x'%(a)
                self.curves[a][0]=self.addCurve(self.plot,pen=pg.mkPen(col, width=1),name='%s:1x'%(a))
                item = self.addLabel(name,col); self.curves[a][0].curve.setClickable(True); self.curves[a][0].sigClicked.connect(functools.partial(self.selectItem,item))

        self.shortlist=[]
        self.menu_entries=[]
        self.menu_group=None
        self.timer = self.newTimer()
        self.timer.timeout.connect(self.locateDevices)
        self.timer.start(500)
项目:pymoskito    作者:cklb    | 项目源码 | 文件源码
def create_plot(self, item):
        """
        Creates a plot widget based on the given item.

        If a plot for this item is already open no new plot is created but the
        existing one is raised up again.

        Args:
            item(Qt.ListItem): Item to plot.
        """
        title = str(item.text())
        if title in self.non_plotting_docks:
            self._logger.error("Title '{}' not allowed for a plot window since"
                               "it would shadow on of the reserved "
                               "names".format(title))

        # check if plot has already been opened
        if title in self.area.findAll()[1]:
            self.area.docks[title].raiseDock()
            return

        # collect data
        data = self._get_data_by_name(title)
        t = self.currentDataset["results"]["time"]
        unit = self._get_units(title)
        if "." in title:
            name = title.split(".")[1]
        else:
            name = title

        # create plot widget
        widget = pg.PlotWidget(title=title)
        widget.showGrid(True, True)
        widget.plot(x=t, y=data)
        widget.getPlotItem().getAxis("bottom").setLabel(text="Time", units="s")
        widget.getPlotItem().getAxis("left").setLabel(text=name, units=unit)

        # add a time line
        time_line = pg.InfiniteLine(self.playbackTime,
                                    angle=90,
                                    movable=False,
                                    pen=pg.mkPen("#FF0000", width=2.0))
        widget.getPlotItem().addItem(time_line)

        # create dock container and add it to dock area
        dock = pg.dockarea.Dock(title, closable=True)
        dock.addWidget(widget)
        self.area.addDock(dock, "above", self.plotDockPlaceholder)
项目:uwb_tracker_ros    作者:bennihepp    | 项目源码 | 文件源码
def update_visualization(self, tofs, ranges, clock_offsets, clock_skews, slave_clock_offset, slave_clock_skew):
        if not self.show_plots:
            return

        import pyqtgraph
        num_of_units = len(tofs)

        # ranges
        while len(self.range_plot) < num_of_units:
            curve_index = len(self.range_plot)
            pen = pyqtgraph.mkPen(curve_index)
            self.range_plot.add_curve(pen=pen, name="{}".format(curve_index))
        for i in xrange(num_of_units):
            self.range_plot.add_point(i, ranges[i])

        # clock offset
        while len(self.clock_offset_plot) < num_of_units:
            curve_index = len(self.clock_offset_plot)
            pen = pyqtgraph.mkPen(curve_index)
            self.clock_offset_plot.add_curve(pen=pen, name="{}".format(curve_index))
        if self.show_slave_clock_offset:
            if len(self.clock_offset_plot) < num_of_units + 1:
                curve_index = len(self.clock_offset_plot)
                pen = pyqtgraph.mkPen(curve_index)
                self.clock_offset_plot.add_curve(pen=pen, name="slave")
        for i in xrange(num_of_units):
            self.clock_offset_plot.add_point(i, clock_offsets[i])
        if self.show_slave_clock_offset:
            self.clock_offset_plot.add_point(len(self.clock_offset_plot) - 1, slave_clock_offset)

        # clock skew
        while len(self.clock_skew_plot) < num_of_units:
            curve_index = len(self.clock_skew_plot)
            pen = pyqtgraph.mkPen(curve_index)
            self.clock_skew_plot.add_curve(pen=pen, name="{}".format(curve_index))
        if self.show_slave_clock_skew:
            if len(self.clock_skew_plot) < num_of_units + 1:
                curve_index = len(self.clock_skew_plot)
                pen = pyqtgraph.mkPen(curve_index)
                self.clock_skew_plot.add_curve(pen=pen, name="slave")
        for i in xrange(num_of_units):
            self.clock_skew_plot.add_point(i, clock_skews[i])
        if self.show_slave_clock_skew:
            self.clock_skew_plot.add_point(len(self.clock_skew_plot) - 1, slave_clock_skew)
项目:CElegansBehaviour    作者:ChristophKirst    | 项目源码 | 文件源码
def plot_trace(xy, ids = None, depth = 0, colormap = 'rainbow', line_color = 'k', line_width = 1, point_size = 5, title = None):
  """Plot trajectories with positions color coded according to discrete ids"""

  #if ids is not None:
  uids = np.unique(ids);

  cmap = cm.get_cmap(colormap);
  n = len(uids);
  colors = cmap(range(n), bytes = True);

  #lines
  if line_width is not None:
    #plt.plot(xy[:,0], xy[:,1], color = lines);    
    plot = pg.plot(xy[:,0], xy[:,1], pen = pg.mkPen(color = line_color, width = line_width))    
  else:
    plot = pg.plot(title = title);

  if ids is None:
    sp = pg.ScatterPlotItem(pos = xy, size=point_size, pen=pg.mkPen(colors[0])); #, pxMode=True);
  else:
    sp = pg.ScatterPlotItem(size=point_size); #, pxMode=True);
    spots = [];
    for j,i in enumerate(uids):
      idx = ids == i;
      spots.append({'pos': xy[idx,:].T, 'data': 1, 'brush':pg.mkBrush(colors[j])}); #, 'size': point_size});
    sp.addPoints(spots)

  plot.addItem(sp);

  return plot;


#  legs = [];
#  for k,i in enumerate(uids):
#    ii = np.where(ids == i)[0];
#    if depth > 0:
#      ii = [ii-d for d in range(depth)];
#      ii = np.unique(np.concatenate(ii));
#    
#    plt.plot(data[ii, 0], data[ii, 1], '.', color = color[k]);
#
#    legs.append(mpatches.Patch(color=color[k], label= str(i)));
#  
#  plt.legend(handles=legs);
项目:CElegansBehaviour    作者:ChristophKirst    | 项目源码 | 文件源码
def plot_trace(xy, ids = None, depth = 0, colormap = 'rainbow', line_color = 'k', line_width = 1, point_size = 5, title = None):
  """Plot trajectories with positions color coded according to discrete ids"""

  #if ids is not None:
  uids = np.unique(ids);

  cmap = cm.get_cmap(colormap);
  n = len(uids);
  colors = cmap(range(n), bytes = True);

  #lines
  if line_width is not None:
    #plt.plot(xy[:,0], xy[:,1], color = lines);    
    plot = pg.plot(xy[:,0], xy[:,1], pen = pg.mkPen(color = line_color, width = line_width))    
  else:
    plot = pg.plot(title = title);

  if ids is None:
    sp = pg.ScatterPlotItem(pos = xy, size=point_size, pen=pg.mkPen(colors[0])); #, pxMode=True);
  else:
    sp = pg.ScatterPlotItem(size=point_size); #, pxMode=True);
    spots = [];
    for j,i in enumerate(uids):
      idx = ids == i;
      spots.append({'pos': xy[idx,:].T, 'data': 1, 'brush':pg.mkBrush(colors[j])}); #, 'size': point_size});
    sp.addPoints(spots)

  plot.addItem(sp);

  return plot;


#  legs = [];
#  for k,i in enumerate(uids):
#    ii = np.where(ids == i)[0];
#    if depth > 0:
#      ii = [ii-d for d in range(depth)];
#      ii = np.unique(np.concatenate(ii));
#    
#    plt.plot(data[ii, 0], data[ii, 1], '.', color = color[k]);
#
#    legs.append(mpatches.Patch(color=color[k], label= str(i)));
#  
#  plt.legend(handles=legs);
项目:pyinduct    作者:pyinduct    | 项目源码 | 文件源码
def shape_generator(self, cls, der_order):
        """
        verify the correct connection with visual feedback
        """

        dz = pi.Domain((0, 1), step=.001)
        dt = pi.Domain((0, 0), num=1)

        nodes, funcs = pi.cure_interval(cls, dz.bounds, node_count=11)
        pi.register_base("test", funcs, overwrite=True)

        # approx_func = pi.Function(np.cos, domain=dz.bounds,
        #                           derivative_handles=[lambda z: -np.sin(z), lambda z: -np.cos(z)])
        approx_func = pi.Function(lambda z: np.sin(3*z), domain=dz.bounds,
                                  derivative_handles=[lambda z: 3*np.cos(3*z), lambda z: -9*np.sin(3*z)])

        weights = approx_func(nodes)

        hull = pi.evaluate_approximation("test", np.atleast_2d(weights),
                                         temp_domain=dt, spat_domain=dz, spat_order=der_order)

        if show_plots:
            # plot shapefunctions
            c_map = pi.visualization.create_colormap(len(funcs))
            pw = pg.plot(title="{}-Test".format(cls.__name__))
            pw.addLegend()
            pw.showGrid(x=True, y=True, alpha=0.5)

            [pw.addItem(pg.PlotDataItem(np.array(dz),
                                        weights[idx]*func.derive(der_order)(dz),
                                        pen=pg.mkPen(color=c_map[idx]),
                                        name="{}.{}".format(cls.__name__, idx)))
             for idx, func in enumerate(funcs)]

            # plot hull curve
            pw.addItem(pg.PlotDataItem(np.array(hull.input_data[1]), hull.output_data[0, :],
                                       pen=pg.mkPen(width=2), name="hull-curve"))
            # plot original function
            pw.addItem(pg.PlotDataItem(np.array(dz), approx_func.derive(der_order)(dz),
                                       pen=pg.mkPen(color="m", width=2, style=pg.QtCore.Qt.DashLine), name="original"))
            pg.QtCore.QCoreApplication.instance().exec_()

        return np.sum(np.abs(hull.output_data[0, :] - approx_func.derive(der_order)(dz)))
项目:kite    作者:pyrocko    | 项目源码 | 文件源码
def __init__(self, sandbox, *args, **kwargs):
        pg.GraphicsLayoutWidget.__init__(self, **kwargs)
        self.sandbox = sandbox

        self.plots = [
            DisplacementPlot(
                sandbox,
                title='North',
                component=lambda m: m.north),
            DisplacementPlot(
                sandbox,
                title='East',
                component=lambda m: m.east),
            DisplacementVectorPlot(
                sandbox,
                title='Down',
                component=lambda m: m.down),
            DisplacementPlot(
                sandbox,
                title='LOS',
                component=lambda m: m.displacement)]
        self.plots[-1].addHintText()

        self._mov_sig = pg.SignalProxy(
            self.scene().sigMouseMoved,
            rateLimit=60, slot=self.mouseMoved)

        for ip, plt in enumerate(self.plots):
            row = ip / 2
            col = ip % 2 + 1

            self.addItem(plt, row=row, col=col)
            plt.showGrid(x=True, y=True)
            plt.hideAxis('bottom')
            plt.hideAxis('left')
            plt.vb.border = pg.mkPen(50, 50, 50)
            if ip != 0:
                plt.setXLink(self.plots[0])
                plt.setYLink(self.plots[0])

        def getAxis(plt, orientation, label):
            axis = pg.AxisItem(
                orientation=orientation,
                linkView=plt.vb)
            axis.setLabel(label, units='m')
            return axis

        plts = self.plots
        self.addItem(getAxis(plts[0], 'left', 'Northing'), row=0, col=0)
        self.addItem(getAxis(plts[1], 'left', 'Northing'), row=1, col=0)
        self.addItem(getAxis(plts[0], 'bottom', 'Easting'), row=2, col=1)
        self.addItem(getAxis(plts[1], 'bottom', 'Easting'), row=2, col=2)

        for plt in self.plots:
            plt.vb.menu = QtGui.QMenu(self)
项目:kite    作者:pyrocko    | 项目源码 | 文件源码
def __init__(self, sandbox, *args, **kwargs):
        pg.GraphicsLayoutWidget.__init__(self, **kwargs)
        self.sandbox = sandbox

        self.plots = [
            DisplacementPlot(
                sandbox,
                title='Scene Displacement',
                component=lambda m: m.reference.scene.displacement),
            DisplacementPlot(
                sandbox,
                title='Model Residual',
                component=lambda m: m.reference.difference)]
        self.plots[-1].addHintText()

        self._mov_sig = pg.SignalProxy(
            self.scene().sigMouseMoved,
            rateLimit=60, slot=self.mouseMoved)

        for ip, plt in enumerate(self.plots):
            row = ip / 2
            col = ip % 2 + 1

            self.addItem(plt, row=row, col=col)
            plt.showGrid(x=True, y=True)
            plt.hideAxis('bottom')
            plt.hideAxis('left')
            plt.vb.border = pg.mkPen(50, 50, 50)
            if ip != 0:
                plt.setXLink(self.plots[0])
                plt.setYLink(self.plots[0])

        def getAxis(plt, orientation, label):
            axis = pg.AxisItem(
                orientation=orientation,
                linkView=plt.vb)
            axis.setLabel(label, units='m')
            return axis

        plts = self.plots
        self.addItem(getAxis(plts[0], 'left', 'Northing'), row=0, col=0)
        self.addItem(getAxis(plts[1], 'left', 'Northing'), row=1, col=0)
        self.addItem(getAxis(plts[0], 'bottom', 'Easting'), row=2, col=1)
        self.addItem(getAxis(plts[1], 'bottom', 'Easting'), row=2, col=2)
项目:specviz    作者:spacetelescope    | 项目源码 | 文件源码
def __init__(self, layer, plot=None, visible=True, style='line',
                 pen=None, err_pen=None, mask_pen=None, color=(0, 0, 0)):
        self._layer = layer
        self.style = style
        self._plot = plot
        self.error = None
        self.mask = None
        self._plot_units = (self._layer.dispersion_unit,
                            self._layer.unit,
                            None)
        self.line_width = 1
        self.mode = None
        self.checked = True

        r, g, b = color
        r, g, b = r * 255, g * 255, b * 255

        rand_pen = pg.mkPen(QColor(r, g, b, 255), width=self.line_width)

        _pen = pg.mkPen(pen, width=self.line_width) if pen is not None else rand_pen

        _inactive_pen = pg.mkPen(QColor(_pen.color().red(),
                                        _pen.color().green(),
                                        _pen.color().blue(),
                                        255))

        _err_pen = err_pen if err_pen is not None else pg.mkPen(
            color=(100, 100, 100, 50))

        _mask_pen = mask_pen if mask_pen is not None else pg.mkPen(
            color=(100, 100, 100, 50))

        self._pen_stash = {'pen_on': pg.mkPen(_pen),
                           'pen_inactive': pg.mkPen(_inactive_pen),
                           'pen_off': pg.mkPen(None),
                           'error_pen_on': _err_pen,
                           'error_pen_off': pg.mkPen(None),
                           'mask_pen_on': _mask_pen,
                           'mask_pen_off': pg.mkPen(None)}

        self.set_plot_visibility(True)
        self.set_error_visibility(True)
        self.set_mask_visibility(False)

        if self._plot is not None:
            self.change_units(self._layer.dispersion_unit,
                              self._layer.unit)
项目:orange-infrared    作者:markotoplak    | 项目源码 | 文件源码
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)