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


Python PlotWidget.viewRange方法代码示例

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


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

示例1: BusMonitorWidget

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

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

        self._load_plot = PlotWidget(background=(0, 0, 0))
        self._load_plot.setRange(xRange=(0, self.DEFAULT_PLOT_X_RANGE), padding=0)
        self._load_plot.setMaximumHeight(150)
        self._load_plot.setMinimumHeight(100)
        self._load_plot.setMinimumWidth(100)
        self._load_plot.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self._load_plot.showGrid(x=True, y=True, alpha=0.4)
        self._load_plot.setToolTip('Frames per second')
        self._load_plot.getPlotItem().getViewBox().setMouseEnabled(x=True, y=False)
        self._load_plot.enableAutoRange()
        self._bus_load_plot = self._load_plot.plot(name='Frames per second', pen=mkPen(QColor(Qt.lightGray), width=1))
        self._bus_load_samples = [], []
        self._started_at_mono = time.monotonic()

        layout = QVBoxLayout(self)

        layout.addWidget(self._log_widget, 1)

        stat_vars_layout = QGridLayout(self)
        stat_layout_next_row = 0

        def add_stat_row(label, value):
            nonlocal stat_layout_next_row
            stat_vars_layout.addWidget(QLabel(label, self), stat_layout_next_row, 0)
            stat_vars_layout.addWidget(value, stat_layout_next_row, 1)
            value.setMinimumWidth(75)
            stat_layout_next_row += 1

        add_stat_row('Frames transmitted:', self._stat_frames_tx)
        add_stat_row('Frames received:', self._stat_frames_rx)
        add_stat_row('Frames per second:', self._stat_traffic)
        stat_vars_layout.setRowStretch(stat_layout_next_row, 1)

        stat_layout = QHBoxLayout(self)
        stat_layout.addLayout(stat_vars_layout)
        stat_layout.addWidget(self._load_plot, 1)

        layout.addLayout(stat_layout, 0)
        self.setLayout(layout)

    def close(self):
        self._hook_handle.remove()

    def _update_stat(self):
        bus_load, ts_mono = self._traffic_stat.get_frames_per_second()
        self._stat_traffic.setText(str(int(bus_load + 0.5)))

        if len(self._bus_load_samples[0]) >= self.BUS_LOAD_PLOT_MAX_SAMPLES:
            self._bus_load_samples[0].pop(0)
            self._bus_load_samples[1].pop(0)

        self._bus_load_samples[1].append(bus_load)
        self._bus_load_samples[0].append(ts_mono - self._started_at_mono)

        self._bus_load_plot.setData(*self._bus_load_samples)

        (xmin, xmax), _ = self._load_plot.viewRange()
        diff = xmax - xmin
        xmax = self._bus_load_samples[0][-1]
        xmin = self._bus_load_samples[0][-1] - diff
        self._load_plot.setRange(xRange=(xmin, xmax), padding=0)

    def _redraw_hook(self):
        self._stat_frames_tx.setText(str(self._traffic_stat.tx))
        self._stat_frames_rx.setText(str(self._traffic_stat.rx))

    def _frame_hook(self, direction, frame):
        self._traffic_stat.add_frame(direction, frame)
        self._log_widget.add_item_async((direction, frame))

    def _update_measurement_display(self, selected_rows_cols):
        if not selected_rows_cols:
            return

        min_row = min([row for row, _ in selected_rows_cols])
        max_row = max([row for row, _ in selected_rows_cols])

        def get_row_ts(row):
            return TimestampRenderer.parse_timestamp(self._log_widget.table.item(row, 1).text())

        def get_load_str(num_frames, dt):
            if dt >= 1e-6:
                return 'average load %.1f FPS' % (num_frames / dt)
            return 'average load is unknown'

        if min_row == max_row:
            num_frames = min_row
            first_ts = get_row_ts(0)
            current_ts = get_row_ts(min_row)
            dt = current_ts - first_ts
            flash(self, '%d frames from beginning, %.3f sec since first frame, %s',
                  num_frames, dt, get_load_str(num_frames, dt))
        else:
            num_frames = max_row - min_row + 1
            first_ts = get_row_ts(min_row)
            last_ts = get_row_ts(max_row)
            dt = last_ts - first_ts
            flash(self, '%d frames, timedelta %.6f sec, %s',
                  num_frames, dt, get_load_str(num_frames, dt))
开发者ID:hsteinhaus,项目名称:gui_tool,代码行数:104,代码来源:bus_monitor.py

示例2: Plotter

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

#.........这里部分代码省略.........
        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):
        # Processing messages
        while True:
            try:
                m = self._message_queue.get_nowait()
                self._process_message(m)
            except queue.Empty:
                break
        # Updating curves
        for curve in self._curves.values():
            if len(curve['x']):
                if len(curve['x']) > self.MAX_DATA_POINTS_PER_CURVE:
                    curve['x'] = curve['x'][-self.MAX_DATA_POINTS_PER_CURVE:]
                    curve['y'] = curve['y'][-self.MAX_DATA_POINTS_PER_CURVE:]
                assert len(curve['x']) == len(curve['y'])
                curve['plot'].setData(curve['x'], curve['y'])
                self._max_x = max(self._max_x, curve['x'][-1])
        # Updating view range
        if self._autoscroll.checkState():
            (xmin, xmax), _ = self._plot_widget.viewRange()
            diff = xmax - xmin
            xmax = self._max_x
            xmin = self._max_x - diff
            self._plot_widget.setRange(xRange=(xmin, xmax), padding=0)


    def _process_message(self, m):
        self._active_messages.add(m.data_type_name)
        for matcher in self._curve_matchers:
            if matcher.match(m):
                name, x, y = matcher.extract_curve_name_x_y(m)
                self._draw_curve(name, x, y)

    def _remove_all_curves(self):
        for curve in self._curves.values():
            self._plot_widget.removeItem(curve['plot'])
        self._plot_widget.clear()
        self._curves = {}
        self._color_index = 0
        self._legend.scene().removeItem(self._legend)
        self._legend = self._plot_widget.addLegend()

    def _draw_curve(self, name, x, y):
        if name not in self._curves:
            logging.info('Adding curve %r', name)
            color = self.COLORS[self._color_index % len(self.COLORS)]
            self._color_index += 1
            pen = mkPen(QColor(color), width=1)
            plot = self._plot_widget.plot(name=name, pen=pen)
            self._curves[name] = {'x': numpy.array([]), 'y': numpy.array([]), 'plot': plot}

        curve = self._curves[name]
        curve['x'] = numpy.append(curve['x'], [x] if isinstance(x, (float, int)) else x)
        curve['y'] = numpy.append(curve['y'], [y] if isinstance(y, (float, int)) else y)
        assert len(curve['x']) == len(curve['y'])

    def push_received_message(self, msg):
        self._message_queue.put_nowait(msg)
开发者ID:hsteinhaus,项目名称:gui_tool,代码行数:104,代码来源:uavcan_plotter.py

示例3: PyQtGraphDataPlot

# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import viewRange [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

示例4: __init__

# 需要导入模块: from pyqtgraph import PlotWidget [as 别名]
# 或者: from pyqtgraph.PlotWidget import viewRange [as 别名]
class Plotter:
    """ This class communicates with the matplotlib library
    and plot the data

    """

    def __init__(self, size):
        """Initialize the plot window, size defines the shape and size
        of the figure
        0 - None, 
        1 - 8x6, 
        11 (default) - 12x8,
        2 - 2 figs 8x8,
        12 - 2 figs 12x8

        """
#        print('ok')
        class CustomViewBox(pg.ViewBox):
           def __init__(self, *args, **kwds):
               pg.ViewBox.__init__(self, *args, **kwds)
               self.setMouseMode(self.RectMode)
        
            ## reimplement right-click to zoom out
           def mouseClickEvent(self, ev):
               if ev.button() == QtCore.Qt.RightButton and QtGui.QApplication.keyboardModifiers()==QtCore.Qt.ControlModifier:
                   self.autoRange()
               else:
                   pg.ViewBox.mouseClickEvent(self, ev)
            
           def mouseDragEvent(self, ev):
               mod = QtGui.QApplication.keyboardModifiers()
               if mod == QtCore.Qt.ControlModifier:
                   self.setMouseMode(self.PanMode)
               else:
                   self.setMouseMode(self.RectMode)
               
               if ev.button() == QtCore.Qt.RightButton:
                   pg.ViewBox.mouseDragEvent(self, ev)
               else:
                   pg.ViewBox.mouseDragEvent(self, ev)

        self.vb = CustomViewBox()
# not necessary?    def clear(self):

    def ylog(self):
        """
           Change y-scale to log
        """
        vr = self._widget.plotItem.viewRange()
        xr = vr[0]
        yr = vr[1]
#        print(xr,yr)
        if yr[0]<=0:
            yr[0]=1
        yr[0]=np.log10(yr[0])
        yr[1]=np.log10(yr[1])
#        print(xr,yr)
        self._widget.plotItem.disableAutoRange()
        self._widget.plotItem.setLogMode(x=False, y=True)
        self._widget.plotItem.setRange(xRange=xr, yRange=yr,padding=None)

    def ylin(self):
        """
           Change y-scale to linear
        """
        vr = self._widget.plotItem.viewRange()
        xr = vr[0]
        yr = vr[1]
#        print(xr,yr)
        yr[0]=10**yr[0]
        yr[1]=10**yr[1]
#        print(xr,yr)
        self._widget.plotItem.disableAutoRange()
        self._widget.plotItem.setLogMode(x=False, y=False)
        self._widget.plotItem.setRange(xRange=xr, yRange=yr,padding=None)

    def plot1d(self, plot, xlim=None, ylim=None):
        """ Plot 1D histogram
            The mode defines the way the data are presented,
            'histogram' is displayed with steps
            'function' with continuus line
            'errorbar' with yerrorbars

            The norm (normalization factor) and bin_size are given
            for the display purposes only. The histogram is not altered.

        """

        histo = plot.histogram

        self._widget = PlotWidget(viewBox=self.vb)
        plt = self._widget.plotItem
        plt.setTitle(histo.title)
        plt.plot(histo.x_axis, histo.weights)
        self._widget.show()
#        if plot.mode == 'histogram':
#            current_plot.plot()
#        win.show()
#        app.processEvents()

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


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