python类mkPen()的实例源码

test_ScatterPlotItem.py 文件源码 项目:NeoAnalysis 作者: neoanalysis 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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()
calibrator.py 文件源码 项目:pslab-desktop-apps 作者: fossasia 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
simulation_gui.py 文件源码 项目:pymoskito 作者: cklb 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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_multi_range_node.py 文件源码 项目:uwb_tracker_ros 作者: bennihepp 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
plot.py 文件源码 项目:CElegansBehaviour 作者: ChristophKirst 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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);
plot.py 文件源码 项目:CElegansBehaviour 作者: ChristophKirst 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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);
test_shapefunctions.py 文件源码 项目:pyinduct 作者: pyinduct 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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)))
multiplot.py 文件源码 项目:kite 作者: pyrocko 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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)
multiplot.py 文件源码 项目:kite 作者: pyrocko 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
plots.py 文件源码 项目:specviz 作者: spacetelescope 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)
owhyper.py 文件源码 项目:orange-infrared 作者: markotoplak 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)


问题


面经


文章

微信
公众号

扫码关注公众号