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

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

项目:pslab-desktop-apps    作者:fossasia    | 项目源码 | 文件源码
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
项目:pslab-desktop-apps    作者:fossasia    | 项目源码 | 文件源码
def removeCurve(self,plot,curve):
        """
        Remove a curve from a plot

        .. tabularcolumns:: |p{3cm}|p{11cm}|

        ===============  ============================================================================================
        **Arguments** 
        ===============  ============================================================================================
        plot             pyqtgraph.PlotWidget created using :func:`add2DPlot`
        name             pyqtgraph.PlotDataItem created for the specified plot using :func:`addCurve`
        ===============  ============================================================================================

        """
        plot.removeItem(curve)
        try:
            self.plots2D[plot].pop(self.plots2D[plot].index(curve))
        except:
            pass
项目:pymoskito    作者:cklb    | 项目源码 | 文件源码
def _update_plots(self):
        """
        Update the data in all plot windows
        """
        for title, dock in self.area.findAll()[1].items():
            if title in self.non_plotting_docks:
                continue

            if not self.dataList.findItems(dock.name(), Qt.MatchExactly):
                # no data for this plot -> remove it
                dock.close()
                continue

            for widget in dock.widgets:
                for item in widget.getPlotItem().items:
                    if isinstance(item, pg.PlotDataItem):
                        x_data = self.currentDataset["results"]["time"]
                        y_data = self._get_data_by_name(dock.name())
                        item.setData(x=x_data, y=y_data)
项目:kite    作者:pyrocko    | 项目源码 | 文件源码
def __init__(self, plot, parent=None):
        QtGui.QDialog.__init__(self, parent)

        loadUi(get_resource('transect.ui'), baseinstance=self)

        pxmap = self.style().standardPixmap

        self.closeButton.setIcon(
            pxmap(QtGui.QStyle.SP_DialogCloseButton))
        self.createButton.setIcon(
            pxmap(QtGui.QStyle.SP_ArrowUp))
        self.removeButton.setIcon(
            pxmap(QtGui.QStyle.SP_DialogDiscardButton))

        self.plot = plot
        self.poly_line = None

        self.trans_plot = pg.PlotDataItem(
            antialias=True,
            fillLevel=0.,
            fillBrush=pg.mkBrush(0, 127, 0, 150))

        self.plt_wdgt = pg.PlotWidget()
        self.plt_wdgt.setLabels(
            bottom={'Distance', 'm'},
            left='Displacement [m]')

        self.plt_wdgt.showGrid(True, True, alpha=.5)
        self.plt_wdgt.enableAutoRange()
        self.plt_wdgt.addItem(self.trans_plot)

        self.layoutPlot.addWidget(self.plt_wdgt)
        self.plot.image.sigImageChanged.connect(self.updateTransPlot)
        self.createButton.released.connect(self.addPolyLine)
        self.removeButton.released.connect(self.removePolyLine)

        parent.model.sigConfigChanged.connect(self.close)
项目:kite    作者:pyrocko    | 项目源码 | 文件源码
def __init__(self, parent_plot):
        _KiteSubplotPlot.__init__(self, parent_plot)

        self.power = pg.PlotDataItem(antialias=True)
        # self.power_lin = pg.PlotDataItem(antialias=True, pen=pen_green_dash)

        self.power.setZValue(10)
        self.plot.setLabels(
            bottom='Wavenumber (cycles/m)',
            left='Power (m<sup>2</sup>)')

        self.plot.setLogMode(x=True, y=True)

        # self.legend = pg.LegendItem(offset=(0., .5))
        # self.legend.setParentItem(self.plot.graphicsItem())
        # self.legend.addItem(self.power_lin, 'Log-linear model')

        self.addItem(self.power)
        # self.addItem(self.power_lin)

        self.model.sigCovarianceChanged.connect(self.update)
        self.update()
项目:kite    作者:pyrocko    | 项目源码 | 文件源码
def __init__(self, parent_plot):
        _KiteSubplotPlot.__init__(self, parent_plot)

        self.structure = pg.PlotDataItem(antialias=True)
        self.variance = pg.InfiniteLine(
            pen=pen_covariance,
            angle=0, movable=True, hoverPen=None,
            label='Variance: {value:.5f}',
            labelOpts={'position': .975,
                       'anchors': ((1., 0.), (1., 1.)),
                       'color': pg.mkColor(255, 255, 255, 155)})
        self.plot.setLabels(bottom={'Distance', 'm'},
                            left='Covariance (m<sup>2</sup>)')

        self.addItem(self.structure)
        self.addItem(self.variance)
        self.model.sigCovarianceChanged.connect(
            self.update)
        self.variance.sigPositionChangeFinished.connect(
            self.changeVariance)

        self.update()
项目:qudi    作者:Ulm-IQO    | 项目源码 | 文件源码
def setup_extraction_ui(self):
        self.lasertrace_image = pg.PlotDataItem(np.array(range(10)), np.zeros(10), pen=palette.c1)
        self._pe.laserpulses_PlotWidget.addItem(self.lasertrace_image)
        self._pe.laserpulses_PlotWidget.addItem(self.sig_start_line)
        self._pe.laserpulses_PlotWidget.addItem(self.sig_end_line)
        self._pe.laserpulses_PlotWidget.addItem(self.ref_start_line)
        self._pe.laserpulses_PlotWidget.addItem(self.ref_end_line)
        self._pe.laserpulses_PlotWidget.setLabel(axis='bottom', text='time', units='s')
项目:pyinduct    作者:pyinduct    | 项目源码 | 文件源码
def __init__(self, data, title="", dt=None):
        PgDataPlot.__init__(self, data)

        self.time_data = [np.atleast_1d(data_set.input_data[0]) for data_set in self._data]
        self.spatial_data = [np.atleast_1d(data_set.input_data[1]) for data_set in self._data]
        self.state_data = [data_set.output_data for data_set in self._data]

        self._pw = pg.plot(title=time.strftime("%H:%M:%S") + ' - ' + title)
        self._pw.addLegend()
        self._pw.showGrid(x=True, y=True, alpha=0.5)

        max_times = [max(data) for data in self.time_data]
        self._endtime = max(max_times)
        self._longest_idx = max_times.index(self._endtime)

        if dt is not None:
            self._dt = dt

        spat_min = np.min([np.min(data) for data in self.spatial_data])
        spat_max = np.max([np.max(data) for data in self.spatial_data])
        self._pw.setXRange(spat_min, spat_max)

        state_min = np.min([np.min(data) for data in self.state_data])
        state_max = np.max([np.max(data) for data in self.state_data])
        self._pw.setYRange(state_min, state_max)

        self._time_text = pg.TextItem('t= 0')
        self._pw.addItem(self._time_text)
        self._time_text.setPos(.9 * spat_max, .9 * state_min)

        self._plot_data_items = []
        for idx, data_set in enumerate(self._data):
            self._plot_data_items.append(pg.PlotDataItem(pen=colors[idx], name=data_set.name))
            self._pw.addItem(self._plot_data_items[-1])

        self._curr_frame = 0
        self._t = 0

        self._timer = pg.QtCore.QTimer()
        self._timer.timeout.connect(self._update_plot)
        self._timer.start(1e3 * self._dt)
项目:kite    作者:pyrocko    | 项目源码 | 文件源码
def __init__(self, parent_plot):
        _KiteSubplotPlot.__init__(self, parent_plot)
        self.plot.setLabels(bottom={'Distance', 'm'},
                            left='Covariance (m<sup>2</sup>)')

        self.cov = pg.PlotDataItem(antialias=True)
        self.cov.setZValue(10)
        self.cov_model = pg.PlotDataItem(antialias=True, pen=pen_covariance)
        self.variance = self.VarianceLine(
            pen=pen_variance,
            angle=0, movable=True, hoverPen=pen_variance_highlight,
            label='Variance: {value:.5f}',
            labelOpts={'position': .975,
                       'anchors': ((1., 0.), (1., 1.)),
                       'color': pg.mkColor(255, 255, 255, 155)})
        self.variance.setToolTip('Move to change variance')

        self.variance.sigPositionChangeFinished.connect(self.setVariance)

        self.addItem(self.variance)

        self.addItem(self.cov)
        self.addItem(self.cov_model)
        # self.cov_lin_pow = pg.PlotDataItem(antialias=True,
        #                                    pen=pen_green_dash)
        # self.addItem(self.cov_lin_pow)

        self.legend = pg.LegendItem(offset=(0., .5))

        self.legend.setParentItem(self.plot.graphicsItem())
        self.legend.addItem(self.cov_model, '')
        self.legend.template = 'Model: {0:.5f} e^(-d/{1:.1f}) | RMS: {rms:.4e}'

        self.model.sigCovarianceChanged.connect(
            self.update)

        self.update()
项目: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 from_layer(layer, **kwargs):
        """Create a LinePlot from a layer

        Parameters
        ----------
        layer: `Spectrum1DRefLayer`
            The layer to create from.

        kwargs: dict
            Other arguments for `LinePlot` class.

        Returns
        -------
        plot_container:
            The new LinePlot
        """
        plot_data_item = pg.PlotDataItem(layer.masked_dispersion, layer.masked_data)

        plot_container = LinePlot(layer=layer, plot=plot_data_item, **kwargs)

        if plot_container.layer.raw_uncertainty is not None:
            plot_error_item = pg.ErrorBarItem(
                x=plot_container.layer.masked_dispersion.compressed().value,
                y=plot_container.layer.masked_data.compressed().value,
                height=plot_container.layer.raw_uncertainty.compressed().value,
            )
            plot_container.error = plot_error_item

        if plot_container.layer.mask is not None:
            mask = plot_container.layer.mask
            x = plot_container.layer.masked_dispersion.data.value[mask]
            y = plot_container.layer.masked_data.data.value[mask]
            plot_mask_item = pg.ScatterPlotItem(
                x=x,
                y=y,
                symbol='x'
            )
            plot_container.mask = plot_mask_item

        return plot_container
项目:qudi    作者:Ulm-IQO    | 项目源码 | 文件源码
def on_activate(self):
        """ Definition and initialisation of the GUI plus staring the measurement.
        """
        self._laser_logic = self.get_connector('laserlogic')

        #####################
        # Configuring the dock widgets
        # Use the inherited class 'CounterMainWindow' to create the GUI window
        self._mw = LaserWindow()

        # Setup dock widgets
        self._mw.setDockNestingEnabled(True)
        self._mw.actionReset_View.triggered.connect(self.restoreDefaultView)

        # set up plot
        self._mw.plotWidget = pg.PlotWidget(
            axisItems={'bottom': TimeAxisItem(orientation='bottom')})
        self._mw.pwContainer.layout().addWidget(self._mw.plotWidget)

        plot1 = self._mw.plotWidget.getPlotItem()
        plot1.setLabel('left', 'power', units='W', color=palette.c1.name())
        plot1.setLabel('bottom', 'Time', units=None)
        plot1.setLabel('right', 'Temperature', units='°C', color=palette.c3.name())

        plot2 = pg.ViewBox()
        plot1.scene().addItem(plot2)
        plot1.getAxis('right').linkToView(plot2)
        plot2.setXLink(plot1)

        self.curves = {}
        colorlist = (palette.c2, palette.c3, palette.c4, palette.c5, palette.c6)
        i = 0
        for name in self._laser_logic.data:
            if name != 'time':
                curve = pg.PlotDataItem()
                if name == 'power':
                    curve.setPen(palette.c1)
                    plot1.addItem(curve)
                else:
                    curve.setPen(colorlist[(2*i) % len(colorlist)])
                    plot2.addItem(curve)
                self.curves[name] = curve
                i += 1

        self.plot1 = plot1
        self.plot2 = plot2
        self.updateViews()
        self.plot1.vb.sigResized.connect(self.updateViews)

        self.updateButtonsEnabled()
        self._mw.laserButton.clicked.connect(self.changeLaserState)
        self._mw.shutterButton.clicked.connect(self.changeShutterState)
        self.sigLaser.connect(self._laser_logic.set_laser_state)
        self.sigShutter.connect(self._laser_logic.set_shutter_state)
        self.sigCurrent.connect(self._laser_logic.set_current)
        self.sigPower.connect(self._laser_logic.set_power)
        self.sigCtrlMode.connect(self._laser_logic.set_control_mode)
        self._mw.controlModeButtonGroup.buttonClicked.connect(self.changeControlMode)
        self.sliderProxy = pg.SignalProxy(self._mw.setValueVerticalSlider.valueChanged, 0.1, 5, self.updateFromSlider)
        self._mw.setValueDoubleSpinBox.editingFinished.connect(self.updateFromSpinBox)
        self._laser_logic.sigUpdate.connect(self.updateGui)
项目: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)))