当前位置: 首页>>代码示例>>Python>>正文


Python PlotWidget.clear方法代码示例

本文整理汇总了Python中pyqtgraph.PlotWidget.clear方法的典型用法代码示例。如果您正苦于以下问题:Python PlotWidget.clear方法的具体用法?Python PlotWidget.clear怎么用?Python PlotWidget.clear使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyqtgraph.PlotWidget的用法示例。


在下文中一共展示了PlotWidget.clear方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: PyQtGraphDataPlot

# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import clear [as 别名]
class PyQtGraphDataPlot(QWidget):

    limits_changed = Signal()

    def __init__(self, parent=None):
        super(PyQtGraphDataPlot, self).__init__(parent)
        self._plot_widget = PlotWidget()
        self._plot_widget.getPlotItem().addLegend()
        self._plot_widget.setBackground((255, 255, 255))
        self._plot_widget.setXRange(0, 10, padding=0)
        vbox = QVBoxLayout()
        vbox.addWidget(self._plot_widget)
        self.setLayout(vbox)
        self._plot_widget.getPlotItem().sigRangeChanged.connect(self.limits_changed)

        self._curves = {}
        self._current_vline = None

    def add_curve(self, curve_id, curve_name, curve_color=QColor(Qt.blue), markers_on=False):
        pen = mkPen(curve_color, width=1)
        symbol = "o"
        symbolPen = mkPen(QColor(Qt.black))
        symbolBrush = mkBrush(curve_color)
        # this adds the item to the plot and legend
        if markers_on:
            plot = self._plot_widget.plot(name=curve_name, pen=pen, symbol=symbol, symbolPen=symbolPen, symbolBrush=symbolBrush, symbolSize=4)
        else:
            plot = self._plot_widget.plot(name=curve_name, pen=pen)
        self._curves[curve_id] = plot

    def remove_curve(self, curve_id):
        curve_id = str(curve_id)
        if curve_id in self._curves:
            self._plot_widget.removeItem(self._curves[curve_id])
            del self._curves[curve_id]
            self._update_legend()
           
    def _update_legend(self):
        # clear and rebuild legend (there is no remove item method for the legend...)
        self._plot_widget.clear()
        self._plot_widget.getPlotItem().legend.items = []
        for curve in self._curves.values():
            self._plot_widget.addItem(curve)
        if self._current_vline:
            self._plot_widget.addItem(self._current_vline)
 
    def redraw(self):
        pass

    def set_values(self, curve_id, data_x, data_y):
        curve = self._curves[curve_id]
        curve.setData(data_x, data_y)

    def vline(self, x, color):
        if self._current_vline:
            self._plot_widget.removeItem(self._current_vline)
        self._current_vline = self._plot_widget.addLine(x=x, pen=color)

    def set_xlim(self, limits):
        # TODO: this doesn't seem to handle fast updates well
        self._plot_widget.setXRange(limits[0], limits[1], padding=0)

    def set_ylim(self, limits):
        self._plot_widget.setYRange(limits[0], limits[1], padding=0)

    def get_xlim(self):
        x_range, _ = self._plot_widget.viewRange()
        return x_range

    def get_ylim(self):
        _, y_range = self._plot_widget.viewRange()
        return y_range
开发者ID:Rescube,项目名称:rqt_common_plugins,代码行数:74,代码来源:pyqtgraph_data_plot.py

示例2: SpectrometerWidget

# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import clear [as 别名]
class SpectrometerWidget(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setLayout(QtGui.QHBoxLayout())
        self.resize(700, 500)
        self.wave = []
        self.spec = []
        self.time = None

        @inlineCallbacks
        def onInit():
            # connect to server
            ipAddress = TEST_SPECTROMETER_SERVER if DEBUG else SPECTROMETER_SERVER
            protocol = yield getProtocol(ipAddress)

            # create a client
            self.client = SpectrometerClient(protocol)
            self.wave = yield self.client.getWavelengths()
            self.numberToAverage = 1
            self.numberAcquired = 0
            self.darkSpectrum = np.zeros(NUM_PIXELS)
            self.specProcessed = np.zeros(NUM_PIXELS)
            self.gettingDark = False

            # set up overall layout: 1 large panel (plot) to left of 1 narrow /
            # panel (controls) all above 1 skinny panel (timestamp)
            fullLayout = QtGui.QVBoxLayout()
            self.layout().addLayout(fullLayout)

            topHalfLayout = QtGui.QHBoxLayout()
            fullLayout.addLayout(topHalfLayout)

            # define the plot
            self.plotWidget = PlotWidget()
            self.plot = self.plotWidget.plot()
            topHalfLayout.addWidget(self.plotWidget, 1)

            # define the controls panel
            cpLayout = QtGui.QVBoxLayout()
            topHalfLayout.addLayout(cpLayout)

            # define the capture controls (to go on controls panel)
            capLayout = QtGui.QVBoxLayout()

            def updatePlot(x, y):
                x = np.asarray(x)
                y = np.asarray(y)
                self.plotWidget.clear()
                self.plotWidget.plot(x, y, pen=mkPen("w", width=1))
                self.plotWidget.addItem(self.cursorVert)
                self.plotWidget.addItem(self.cursorHori)
                vertLabel.setText(str(round(self.cursorVert.pos()[0], 2)))
                horiLabel.setText(str(round(self.cursorHori.pos()[1], 2)))

            def avgSpec():
                oldAvgSpec = self.specProcessed
                addThis = self.spec - self.darkSpectrum
                self.numberAcquired += 1
                if self.numberAcquired < self.numberToAverage:
                    scale = self.numberAcquired
                else:
                    scale = self.numberToAverage
                newAvg = ((scale - 1) * oldAvgSpec + addThis) / scale
                self.specProcessed = newAvg

            @inlineCallbacks
            def capture():
                self.spec = yield self.client.getSpectrum()
                self.spec = np.asarray(self.spec)
                self.time = yield self.client.getLastTime()
                yield avgSpec()
                updatePlot(self.wave, self.specProcessed)
                self.timestamp.setText("last update: " + str(self.time))

            @inlineCallbacks
            def forcePress():
                self.numberAcquired = 0
                yield capture()

            forceButton = QtGui.QPushButton("force")
            forceButton.clicked.connect(forcePress)
            capLayout.addWidget(forceButton)

            autoRunLayout = QtGui.QHBoxLayout()

            self.freeRunCall = LoopingCall(capture)
            self.freeRunStatus = False

            def freeRun():
                if self.freeRunStatus:
                    freeButton.setText("start auto")
                    forceButton.setEnabled(True)
                    self.freeRunCall.stop()
                    self.freeRunStatus = False
                    self.numberAcquired = 0
                    return
                if not self.freeRunStatus:
                    freeButton.setText("stop auto")
                    forceButton.setEnabled(False)
                    self.freeRunCall.start(autoRateSpin.value(), now=True)
#.........这里部分代码省略.........
开发者ID:stevens4,项目名称:sitzlabexpcontrol,代码行数:103,代码来源:spectrometergui.py

示例3: Plotter

# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import clear [as 别名]
class Plotter(QWidget):
    MAX_DATA_POINTS_PER_CURVE = 200000

    COLORS = [Qt.red, Qt.green, Qt.blue,                        # RGB - http://ux.stackexchange.com/questions/79561
              Qt.yellow, Qt.cyan, Qt.magenta,                   # Close to RGB
              Qt.darkRed, Qt.darkGreen, Qt.darkBlue,            # Darker RGB
              Qt.darkYellow, Qt.darkCyan, Qt.darkMagenta,       # Close to RGB
              Qt.gray, Qt.darkGray]                             # Leftovers

    INITIAL_X_RANGE = 60

    def __init__(self, parent=None):
        # Parent
        super(Plotter, self).__init__(parent)
        self.setWindowTitle('UAVCAN Plotter')
        self.setWindowIcon(APP_ICON)

        # Redraw timer
        self._update_timer = QTimer()
        self._update_timer.timeout.connect(self._update)
        self._update_timer.setSingleShot(False)
        self._update_timer.start(30)

        # PyQtGraph
        self._plot_widget = PlotWidget()
        self._plot_widget.setBackground((0, 0, 0))
        self._legend = self._plot_widget.addLegend()
        self._plot_widget.setRange(xRange=(0, self.INITIAL_X_RANGE), padding=0)
        self._plot_widget.showButtons()
        self._plot_widget.enableAutoRange()
        self._plot_widget.showGrid(x=True, y=True, alpha=0.4)

        # Controls
        # https://specifications.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
        button_add_matcher = QtGui.QPushButton('New matcher', self)
        button_add_matcher.setIcon(QtGui.QIcon.fromTheme('list-add'))
        button_add_matcher.setToolTip('Add new curve matcher')
        button_add_matcher.clicked.connect(
            lambda: NewCurveMatcherWindow(self, lambda: sorted(self._active_messages), self._add_curve_matcher).show())

        button_clear_plots = QtGui.QPushButton('Clear plots', self)
        button_clear_plots.setIcon(QtGui.QIcon.fromTheme('edit-clear'))
        button_clear_plots.setToolTip('Clear the plotting area')
        button_clear_plots.clicked.connect(lambda: self._remove_all_curves())

        def delete_all_matchers():
            self._curve_matchers = []
            for i in reversed(range(self._curve_matcher_container.count())):
                self._curve_matcher_container.itemAt(i).widget().deleteLater()
            self._remove_all_curves()

        button_delete_all_matchers = QtGui.QPushButton('Delete matchers', self)
        button_delete_all_matchers.setIcon(QtGui.QIcon.fromTheme('edit-delete'))
        button_delete_all_matchers.setToolTip('Delete all matchers')
        button_delete_all_matchers.clicked.connect(delete_all_matchers)

        self._autoscroll = QtGui.QCheckBox('Autoscroll', self)
        self._autoscroll.setChecked(True)
        self._max_x = self.INITIAL_X_RANGE

        # Layout
        control_panel = QHBoxLayout()
        control_panel.addWidget(button_add_matcher)
        control_panel.addWidget(button_clear_plots)
        control_panel.addWidget(self._autoscroll)
        control_panel.addStretch()
        control_panel.addWidget(button_delete_all_matchers)

        self._curve_matcher_container = QVBoxLayout()

        layout = QVBoxLayout()
        layout.addWidget(self._plot_widget, 1)
        layout.addLayout(control_panel)
        layout.addLayout(self._curve_matcher_container)
        self.setLayout(layout)

        # Logic
        self._color_index = 0
        self._curves = {}
        self._message_queue = multiprocessing.Queue()
        self._active_messages = set() # set(data type name)
        self._curve_matchers = []

        # Defaults
        self._add_curve_matcher(CurveMatcher('uavcan.protocol.debug.KeyValue', 'value', [('key', None)]))

    def _add_curve_matcher(self, matcher):
        self._curve_matchers.append(matcher)
        view = CurveMatcherView(matcher, self)

        def remove():
            self._curve_matchers.remove(matcher)
            self._curve_matcher_container.removeWidget(view)
            view.setParent(None)
            view.deleteLater()

        view.on_remove = remove
        self._curve_matcher_container.addWidget(view)

    def _update(self):
#.........这里部分代码省略.........
开发者ID:hsteinhaus,项目名称:gui_tool,代码行数:103,代码来源:uavcan_plotter.py

示例4: SmartScanGUI

# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import clear [as 别名]
class SmartScanGUI(QtGui.QWidget):
    # oh god i'm so sorry. don't listen to him; he's never sorry.
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setLayout(QtGui.QHBoxLayout())
        
        # a dict to store data
        self.dataMatrix = {}
        self.refData = {}
        
        ########################################## create a plot and associated widget ###########################################################
        self.plotWidget = PlotWidget()
        self.layout().addWidget(self.plotWidget,1)
        
        def xYPlot(plotWidget,x,y,yerr=None,xerr=None,color='w',name='Current'):
            thisPlot = plotWidget.plot(x,y,pen=mkPen(color,width=2))
            plotWidget.addItem(
                ErrorBarItem(
                    x=np.asarray(x),
                    y=np.asarray(y),
                    top=np.asarray(yerr) if yerr is not None else None,
                    bottom=np.asarray(yerr) if yerr is not None else None,
                    left=np.asarray(xerr) if xerr is not None else None,
                    right=np.asarray(xerr) if xerr is not None else None,
                    beam=.05,
                    pen=mkPen(color)
                )
            )
            
        # method for updating plot with new data (plot has to be cleared first)
        def updatePlot():
            self.plotWidget.clear()
            for name, rData in self.refData.iteritems():
                xYPlot(
                    self.plotWidget,
                    rData['data'][0],
                    rData['data'][1],
                    yerr=rData['data'][2],
                    color=rData['color'],
                    name=name
                )
            if len(self.dataMatrix.keys()) >= 1:
                for xVal, yValues in self.dataMatrix.items():
                    if xVal in self.xVals:
                        oldMean = self.yVals[self.xVals.index(xVal)]
                        thisMean = np.mean(yValues)
                        newMean = (oldMean+thisMean)/2.
                        self.yVals[self.xVals.index(xVal)] = newMean
                        newErr = np.std(yValues)/np.sqrt(len(yValues))
                        self.errVals[self.xVals.index(xVal)] = newErr
                    else:
                        self.xVals.append(xVal)
                        mean = np.mean(yValues)
                        self.yVals.append(mean)
                        err = np.std(yValues)/np.sqrt(len(yValues))
                        self.errVals.append(err)
                xYPlot(self.plotWidget,self.xVals,self.yVals,yerr=self.errVals) 

        
        ############################################## configure a control panel layout ########################################################
        cpLayout = QtGui.QVBoxLayout()
        self.layout().addLayout(cpLayout)

        # configure the output widget
        outputPane = QtGui.QTabWidget()
        cpLayout.addWidget(LabelWidget('output',outputPane))


            
        @inlineCallbacks
        def onInit():
            ############################################################# VOLTMETER OUTPUT ###########################################################
            # add volt meter to scan output
            if DEBUG:
                vmURL = TEST_VOLTMETER_SERVER
            else:
                vmURL = VOLTMETER_SERVER
            vmProtocol = yield getProtocol(vmURL)
            vmClient = VoltMeterClient(vmProtocol)    
            vmWidget = VoltMeterOutputWidget(vmClient)
            outputPane.addTab(vmWidget,'voltmeter')


            ############################################################# BEGIN INPUTS ###########################################################

            # configure the input widget
            inputPane = QtGui.QTabWidget()
            inputPane.setTabPosition(inputPane.West)
            cpLayout.addWidget(LabelWidget('input',inputPane),1)    

            
            # algorithm for scan inputs is:
            # 0. check to see if input is disabled
            # 1. create client for server from protocol object
            # 2. create combo widget to hold interval and list widgets
            # 3. create interval widget using client object, add to combo
            # 4. same for list widget
            # 5. add combo widget to base combo widget (resulting in 2-D tab widget)

            
#.........这里部分代码省略.........
开发者ID:stevens4,项目名称:sitzlabexpcontrol,代码行数:103,代码来源:iScan.py

示例5: Aditi

# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import clear [as 别名]

#.........这里部分代码省略.........

    def handle_key_press_event(self, evt):
        if self.inf_line_tic_item is None:
            return

        times = []
        if evt.key() == Qt.Key_Left:
            for rawfile in self.rawfiles_by_short_path.values()[:1]:
                if not rawfile.is_checked:
                    continue
                curr_scan_id = self.curr_scan_id_by_short_path[rawfile.short_path]
                scan_ids = rawfile.reader.rt_by_scan_id_by_ms_level[1].keys()
                idx = scan_ids.index(curr_scan_id)
                times.append(rawfile.reader.rt_by_scan_id_by_ms_level[1][scan_ids[idx - 1]])
                self.curr_scan_id_by_short_path[rawfile.short_path] = scan_ids[idx - 1]

        elif evt.key() == Qt.Key_Right:
            for rawfile in self.rawfiles_by_short_path.values()[:1]:
                if not rawfile.is_checked:
                    continue
                curr_scan_id = self.curr_scan_id_by_short_path[rawfile.short_path]
                scan_ids = rawfile.reader.rt_by_scan_id_by_ms_level[1].keys()
                idx = scan_ids.index(curr_scan_id)
                times.append(rawfile.reader.rt_by_scan_id_by_ms_level[1][scan_ids[idx + 1]])
                self.curr_scan_id_by_short_path[rawfile.short_path] = scan_ids[idx + 1]

        self._plot_spectrum()

        if times:
            self.inf_line_tic_item.setPos(sum(times) / float(len(times)))

    def _plot_spectrum(self):

        self.plot_widget_spectrum.clear()

        min_mz, max_mz = 1e9, 0
        min_int, max_int = 1e10, 0

        for rawfile in self.rawfiles_by_short_path.values():
            if not rawfile.is_checked:
                continue
            scan_id, mzs, intensities = rawfile.reader.get_scan(self.curr_scan_id_by_short_path[rawfile.short_path])
            min_mz = min(min_mz, mzs[0])
            max_mz = max(max_mz, mzs[-1])
            min_int = min(min_int, min(intensities))
            max_int = max(max_int, max(intensities))
            item = BarGraphItem(x=mzs, height=intensities, width=0.01, pen=rawfile.qcolor, brush=rawfile.qcolor)
            self.plot_widget_spectrum.addItem(item)

        self.plot_widget_spectrum.setLimits(xMin=min_mz, xMax=max_mz, yMin=min_int, yMax=max_int)

    def plot_spectrum(self, ev):
        #clear
        if ev.button() == Qt.RightButton:
            return

        self.plot_widget_spectrum.clear()

        vb = self.plot_widget_tic.vb
        mouse_point = vb.mapSceneToView(ev.scenePos())
        t = mouse_point.x()
        if self.inf_line_tic_item is None:
            self.inf_line_tic_item = InfiniteLine(pos=t, angle=90)
            self.plot_widget_tic.addItem(self.inf_line_tic_item)
            self.inf_line_tic_item.setMovable(True)
        else:
开发者ID:jerkos,项目名称:pymzdb,代码行数:70,代码来源:aditi.py


注:本文中的pyqtgraph.PlotWidget.clear方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。