Python pyqtgraph.ScatterPlotItem() Examples

The following are 25 code examples of pyqtgraph.ScatterPlotItem(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyqtgraph , or try the search function .
Example #1
Source File: tab_aps.py    From kite with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, parent_plot):
        KiteSubplot.__init__(self, parent_plot)

        self.aps_correlation = pg.ScatterPlotItem(
            antialias=True,
            brush=brush_aps,
            pen=pen_aps,
            size=4)

        self.aps_model = pg.PlotDataItem(
            antialias=True,
            pen=pen_aps_model)

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

        self.legend.setParentItem(self.plot.graphicsItem())
        self.legend.addItem(self.aps_model, '')

        self.addItem(self.aps_correlation)
        self.addItem(self.aps_model)

        self.plot.setLabels(
            bottom='Elevation (m)',
            left='Displacement (m)') 
Example #2
Source File: AttributeCharts.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, iface, plot):
        QObject.__init__(self)

        self.iface = iface
        self.plot = plot
        self.add_selection = False
        self.just_selected = False
        self.show_lines = True

        if has_pyqtgraph:
            self.plot.setClipToView(True)
            self.plot.enableAutoRange(enable=True)
            self.hist_selection = pg.PlotCurveItem()
            self.scatter_selection = []
            self.scatter = pg.ScatterPlotItem()
            self.scatter_points = {}
            self.region = pg.LinearRegionItem()
            #self.selected_points = []
            self.selected_points = pg.ScatterPlotItem()
            self.regress_line = pg.InfiniteLine()
            #self.roi = None

    #----
    # Histogram functions 
Example #3
Source File: onlinetraceviewer.py    From tridesclous with MIT License 6 votes vote down vote up
def change_catalogue(self, catalogue):
        with self.mutex:
            
            for k, v in self.scatters.items():
                self.plot.removeItem(v)
            self.scatters = {}
            
            self.catalogue = catalogue

            colors = make_color_dict(self.catalogue['clusters'])
            
            self.qcolors = {}
            for k, color in colors.items():
                r, g, b = color
                self.qcolors[k] = QT.QColor(r*255, g*255, b*255)
            
            self.all_plotted_labels = self.catalogue['cluster_labels'].tolist() + [LABEL_UNCLASSIFIED]
            
            for k in self.all_plotted_labels:
                qcolor = self.qcolors[k]
                qcolor.setAlpha(150)
                scatter = pg.ScatterPlotItem(x=[ ], y= [ ], pen=None, brush=qcolor, size=10, pxMode = True)
                self.scatters[k] = scatter
                self.plot.addItem(scatter) 
Example #4
Source File: ScatterPlotSpeedTest.py    From tf-pose with Apache License 2.0 5 votes vote down vote up
def update():
    global curve, data, ptr, p, lastTime, fps
    p.clear()
    if ui.randCheck.isChecked():
        size = sizeArray
    else:
        size = ui.sizeSpin.value()
    curve = pg.ScatterPlotItem(x=data[ptr%50], y=data[(ptr+1)%50], 
                               pen='w', brush='b', size=size, 
                               pxMode=ui.pixelModeCheck.isChecked())
    p.addItem(curve)
    ptr += 1
    now = time()
    dt = now - lastTime
    lastTime = now
    if fps is None:
        fps = 1.0/dt
    else:
        s = np.clip(dt*3., 0, 1)
        fps = fps * (1-s) + (1.0/dt) * s
    p.setTitle('%0.2f fps' % fps)
    p.repaint()
    #app.processEvents()  ## force complete redraw for every plot 
Example #5
Source File: AttributeCharts.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def clearScatterplotSelection(self):
        if has_pyqtgraph:
            if self.selected_points:
                self.plot.removeItem(self.selected_points)
                self.selected_points = pg.ScatterPlotItem()
                self.scatter_selection = [] 
Example #6
Source File: AttributeCharts.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def setScatterplotSelection(self, xvalues, yvalues, ids):
        if has_pyqtgraph:
            #if not self.just_selected:
            self.clearScatterplotSelection()
            if len(ids) > 0:
                self.scatter_selection = [fid for fid in ids]
                self.selected_points = pg.ScatterPlotItem()
                self.selected_points.addPoints(x=xvalues, y=yvalues, data=ids, size=3, pen=pg.mkPen('r', width=1), brush=pg.mkBrush(235, 0, 0, 255))
                self.plot.addItem(self.selected_points)
            self.just_selected = False 
Example #7
Source File: AttributeCharts.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def drawScatterplot(self, xvalues, xmin, xmax, yvalues, ymin, ymax, slope, intercept, ids, symbols=None):
        # plot the chart
        if has_pyqtgraph:
            self.scatter = pg.ScatterPlotItem()
            self.plot.clear()
            # each point takes the colour of the map
            if symbols:
                points = []
                for i, id in enumerate(ids):
                    x = xvalues[i]
                    y = yvalues[i]
                    symb = symbols[i]
                    points.append({'pos': (x,y), 'data': id, 'size': 3, 'pen': pg.mkPen(None), 'brush': symb})
                self.scatter.addPoints(points)
            else:
                self.scatter.addPoints(x=xvalues, y=yvalues, data=ids, size=3, pen=pg.mkPen(None), brush=pg.mkBrush(235, 235, 235, 255))
            # selection by direct click
            self.scatter.sigClicked.connect(self.changedScatterplotSelection)
            self.plot.addItem(self.scatter)
            # add the regression line
            self.regress_line = pg.InfiniteLine()
            self.regress_line.setAngle(atan(slope/1) * 180 / 3.1459)
            self.regress_line.setValue((0,intercept))
            self.regress_line.setPen(color='b', width=1)
            if self.show_lines:
                self.plot.addItem(self.regress_line)
            # newfeature: add the selection tool
            #self.roi = pg.PolyLineROI([[xmin, ymin],[xmax, ymin],[xmax, ymax],[xmin, ymax]], closed=True)
            #self.roi.sigRegionChangeFinished.connect(self.changedScatterPlotSelection)
            #self.plot.addItem(self.roi)
            #self.plot.disableAutoRange('xy')

    # allow selection of items in chart and selecting them on the map 
Example #8
Source File: test_ScatterPlotItem.py    From soapy with GNU General Public License v3.0 5 votes vote down vote up
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' 
Example #9
Source File: OWAnnotateProjection.py    From orange3-bioinformatics with GNU General Public License v3.0 5 votes vote down vote up
def update_reference_coordinates(self):
        points = self.master.get_coordinates_reference_data()
        if points is None:
            return
        if self.ref_scatterplot_item is None:
            color = pg.mkColor(200, 200, 200)
            pen, brush = pg.mkPen(color=color), pg.mkBrush(color=color)
            size = OWScatterPlotBase.MinShapeSize + 3
            self.ref_scatterplot_item = pg.ScatterPlotItem(x=points[0], y=points[1], pen=pen, brush=brush, size=size)
            self.plot_widget.addItem(self.ref_scatterplot_item)
        else:
            self.ref_scatterplot_item.setData(x=points[0], y=points[1]) 
Example #10
Source File: drawroi.py    From suite2p with GNU General Public License v3.0 5 votes vote down vote up
def proc_ROI(self):
        stat0 = []
        if self.extracted:
            for t, s in zip(self.scatter, self.tlabel):
                self.p0.removeItem(s)
                self.p0.removeItem(t)
        self.scatter = []
        self.tlabel = []
        for n in range(self.nROIs):
            ellipse = self.ROIs[n].ellipse
            yrange = self.ROIs[n].yrange
            xrange = self.ROIs[n].xrange
            x, y = np.meshgrid(xrange, yrange)
            ypix = y[ellipse].flatten()
            xpix = x[ellipse].flatten()
            lam = np.ones(ypix.shape)
            stat0.append({'ypix': ypix, 'xpix': xpix, 'lam': lam, 'npix': ypix.size})
            self.tlabel.append(pg.TextItem(str(n), self.ROIs[n].color, anchor=(0, 0)))
            self.tlabel[-1].setPos(xpix.mean(), ypix.mean())
            self.p0.addItem(self.tlabel[-1])
            self.scatter.append(pg.ScatterPlotItem([xpix.mean()], [ypix.mean()],
                                                   pen=self.ROIs[n].color, symbol='+'))
            self.p0.addItem(self.scatter[-1])
        if not os.path.isfile(self.parent.ops['reg_file']):
            self.parent.ops['reg_file'] = os.path.join(self.parent.basename, 'data.bin')

        F, Fneu, F_chan2, Fneu_chan2, spks, ops, stat = masks_and_traces(self.parent.ops, stat0, self.parent.stat)
        print(spks.shape)
        # print('After', stat[0].keys())
        # print('Orig', self.parent.stat[0].keys())
        self.Fcell = F
        self.Fneu = Fneu
        self.F_chan2 = F_chan2
        self.Fneu_chan2 = Fneu_chan2
        self.Spks = spks
        self.plot_trace()
        self.extracted = True
        self.new_stat = stat
        self.closeGUI.setEnabled(True) 
Example #11
Source File: merge.py    From suite2p with GNU General Public License v3.0 5 votes vote down vote up
def suggest_merge(self, parent):
        parent.ichosen = self.merge_list[self.n][0]
        parent.imerge  = list(self.merge_list[self.n])
        if self.unmerged[self.n]:
            self.iMerge.setText('suggested ROIs to merge: %s'%parent.imerge)
            self.doMerge.setEnabled(True)
            self.p0.clear()
            cell0 = parent.imerge[0]
            sstring = ''
            for i in parent.imerge[1:]:
                rgb = parent.colors['cols'][0,i]
                pen = pg.mkPen(rgb, width=3)
                scatter=pg.ScatterPlotItem(parent.Fbin[cell0], parent.Fbin[i], pen=pen)
                self.p0.addItem(scatter)
                sstring += ' %d '%i
            self.p0.setLabel('left', sstring)
            self.p0.setLabel('bottom', str(cell0))
        else:
            # set to the merged ROI index
            parent.ichosen = parent.stat[parent.ichosen]['inmerge']
            parent.imerge = [parent.ichosen]
            self.iMerge.setText('ROIs merged: %s'%list(parent.stat[parent.ichosen]['imerge']))
            self.doMerge.setEnabled(False)
            self.p0.clear()

        self.n+=1
        if self.n > len(self.merge_list)-1:
            self.n = 0
        parent.checkBoxz.setChecked(True)
        parent.update_plot()
        parent.win.show()
        parent.show() 
Example #12
Source File: camera_display.py    From stytra with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.points_fish = pg.ScatterPlotItem(
            size=5, pxMode=True, brush=(255, 0, 0), pen=None
        )
        self.lines_fish = pg.PlotCurveItem(
            connect="pairs", pen=pg.mkPen((10, 100, 200), width=3)
        )
        self.display_area.addItem(self.points_fish)
        self.display_area.addItem(self.lines_fish)
        self.tracking_params = self.experiment.pipeline.fishtrack._params 
Example #13
Source File: camera_display.py    From stytra with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.points_calib = pg.ScatterPlotItem()
        self.display_area.addItem(self.points_calib) 
Example #14
Source File: test_ScatterPlotItem.py    From tf-pose with Apache License 2.0 5 votes vote down vote up
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' 
Example #15
Source File: reggui.py    From suite2p with GNU General Public License v3.0 4 votes vote down vote up
def plot_frame(self):
        if self.loaded:
            self.titles[0].setText('difference')
            self.titles[1].setText('merged')
            self.titles[2].setText('top')
            iPC = int(self.PCedit.text()) - 1
            pc1 = self.PC[1,iPC,:,:]
            pc0 = self.PC[0,iPC,:,:]
            self.img0.setImage(np.tile(pc1[:,:,np.newaxis]-pc0[:,:,np.newaxis],(1,1,3)))
            self.img0.setLevels([(pc1-pc0).min(),(pc1-pc0).max()])
            rgb = np.zeros((self.PC.shape[2], self.PC.shape[3],3), np.float32)
            rgb[:,:,0] = (pc1-pc1.min())/(pc1.max()-pc1.min())*255
            rgb[:,:,1] = np.minimum(1, np.maximum(0,(pc0-pc1.min())/(pc1.max()-pc1.min())))*255
            rgb[:,:,2] = (pc1-pc1.min())/(pc1.max()-pc1.min())*255
            self.img1.setImage(rgb)
            if self.cframe==0:
                self.img2.setImage(np.tile(pc0[:,:,np.newaxis],(1,1,3)))
            else:
                self.img2.setImage(np.tile(pc1[:,:,np.newaxis],(1,1,3)))
            self.img2.setLevels([pc0.min(),pc0.max()])
            self.zoom_plot()
            self.p3.clear()
            p = [(200,200,255),(255,100,100),(100,50,200)]
            ptitle = ['rigid','nonrigid','nonrigid max']
            if not hasattr(self,'leg'):
                self.leg = pg.LegendItem((100,60),offset=(350,30))
                self.leg.setParentItem(self.p3)
                drawLeg = True
            else:
                drawLeg = False
            for j in range(3):
                cj = self.p3.plot(np.arange(1,self.nPCs+1),self.DX[:,j],pen=p[j])
                if drawLeg:
                    self.leg.addItem(cj,ptitle[j])
                self.nums[j].setText('%s: %1.3f'%(ptitle[j],self.DX[iPC,j]))
            self.scatter = pg.ScatterPlotItem()
            self.p3.addItem(self.scatter)
            self.scatter.setData([iPC+1,iPC+1,iPC+1],self.DX[iPC,:].tolist(),
                                 size=10,brush=pg.mkBrush(255,255,255))
            self.p3.setLabel('left', 'pixel shift')
            self.p3.setLabel('bottom', 'PC #')

            self.p4.clear()
            self.p4.plot(self.tPC[:,iPC])
            self.p4.setLabel('left', 'magnitude')
            self.p4.setLabel('bottom', 'time')
            self.show()
            self.zoom_plot() 
Example #16
Source File: monitor_control.py    From stytra with GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, *args, display_size=(1280, 800), display, **kwargs):
        super().__init__(*args, **kwargs)

        self.display = display

        self.view_box = pg.ViewBox(invertY=True, lockAspect=1, enableMouse=False)
        self.addItem(self.view_box)

        self.roi_box = pg.ROI(
            maxBounds=QRectF(0, 0, display_size[0], display_size[1]),
            size=display.size,
            pos=display.pos,
        )

        self.roi_box.addScaleHandle([0, 0], [1, 1])
        self.roi_box.addScaleHandle([1, 1], [0, 0])
        self.roi_box.sigRegionChanged.connect(self.set_param_val)
        self.display.sig_param_changed.connect(self.set_roi)
        self.view_box.addItem(self.roi_box)
        self.view_box.setRange(
            QRectF(0, 0, display_size[0], display_size[1]),
            update=True,
            disableAutoRange=True,
        )
        self.view_box.addItem(
            pg.ROI(
                pos=(1, 1),
                size=(display_size[0] - 1, display_size[1] - 1),
                movable=False,
                pen=(80, 80, 80),
            )
        )

        self.calibration_points = pg.ScatterPlotItem(pen=(255, 0, 0), brush=None)
        self.calibration_frame = pg.PlotCurveItem(
            brush=(120, 10, 10), pen=(200, 10, 10), fill_level=1
        )

        self.camera_image = pg.ImageItem()

        self.view_box.addItem(self.calibration_frame)
        self.view_box.addItem(self.camera_image)
        self.view_box.addItem(self.calibration_points)

        self.setting_param_val = False

        self.set_param_val() 
Example #17
Source File: plottrigger.py    From eegsynth with GNU General Public License v3.0 4 votes vote down vote up
def _loop_once():
    '''Run the main loop once
    This uses the global variables from setup and start, and adds a set of global variables
    '''
    global parser, args, config, r, response, patch
    global monitor, debug, delay, window, value, winx, winy, winwidth, winheight, data, lock, trigger, number, i, this, thread, app, win, plot

    monitor.loop()

    now = time.time()
    plot.clear()
    for y in number:
        for event in data[y]:
            x = event[0] - now      # time
            v = event[1]            # value

            if x < -window-0.5:
                # remove the event if it is too far in the past
                data[y].remove(event)
                continue

            scatter = pg.ScatterPlotItem()
            scatter.addPoints([{'pos': (x, y)}])
            plot.addItem(scatter)

            if value:
                # show the numeric value next to the trigger

                if abs(v-round(v))<0.001:
                    # print it as integer value
                    s = '%d' % v
                else:
                    # print it as floating point value
                    s = '%2.1f' % v

                text = pg.TextItem(s, anchor=(0,0))
                text.setPos(x, y)
                plot.addItem(text)

    signal.signal(signal.SIGINT, _stop)

    # Set timer for update
    timer = QtCore.QTimer()
    timer.timeout.connect(_loop_once)
    timer.setInterval(10)                     # timeout in milliseconds
    timer.start(int(round(delay * 1000)))     # in milliseconds

    # there should not be any local variables in this function, they should all be global
    if len(locals()):
        print('LOCALS: ' + ', '.join(locals().keys())) 
Example #18
Source File: test_ScatterPlotItem.py    From soapy with GNU General Public License v3.0 4 votes vote down vote up
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() 
Example #19
Source File: traceviewer.py    From tridesclous with MIT License 4 votes vote down vote up
def initialize_plot(self):
        self.viewBox = MyViewBox()
        self.plot = pg.PlotItem(viewBox=self.viewBox)
        self.graphicsview.setCentralItem(self.plot)
        self.plot.hideButtons()
        self.plot.showAxis('left', False)
        
        self.viewBox.gain_zoom.connect(self.gain_zoom)
        self.viewBox.xsize_zoom.connect(self.xsize_zoom)
        
        self.visible_channels = np.zeros(self.controller.nb_channel, dtype='bool')
        self.max_channel = min(16, self.controller.nb_channel)
        #~ self.max_channel = min(5, self.controller.nb_channel)
        if self.controller.nb_channel>self.max_channel:
            self.visible_channels[:self.max_channel] = True
            self.scroll_chan.show()
            self.scroll_chan.setMinimum(0)
            self.scroll_chan.setMaximum(self.controller.nb_channel-self.max_channel)
            self.scroll_chan.setPageStep(self.max_channel)
        else:
            self.visible_channels[:] = True
            self.scroll_chan.hide()
            
        self.signals_curve = pg.PlotCurveItem(pen='#7FFF00', connect='finite')
        self.plot.addItem(self.signals_curve)

        self.scatter = pg.ScatterPlotItem(size=10, pxMode = True)
        self.plot.addItem(self.scatter)
        self.scatter.sigClicked.connect(self.scatter_item_clicked)
        
        self.channel_labels = []
        self.threshold_lines =[]
        for i, chan_name in enumerate(self.controller.channel_names):
            #TODO label channels
            label = pg.TextItem('{}: {}'.format(i, chan_name), color='#FFFFFF', anchor=(0, 0.5), border=None, fill=pg.mkColor((128,128,128, 180)))
            self.plot.addItem(label)
            self.channel_labels.append(label)
        
        
        for i in range(self.max_channel):
            tc = pg.InfiniteLine(angle = 0., movable = False, pen = pg.mkPen(color=(128,128,128, 120)))
            tc.setPos(0.)
            self.threshold_lines.append(tc)
            self.plot.addItem(tc)
            tc.hide()
        
        pen = pg.mkPen(color=(128,0,128, 120), width=3, style=QT.Qt.DashLine)
        self.selection_line = pg.InfiniteLine(pos = 0., angle=90, movable=False, pen = pen)
        self.plot.addItem(self.selection_line)
        self.selection_line.hide()
        
        self._initialize_plot()
        
        self.gains = None
        self.offsets = None 
Example #20
Source File: tab_quadtree.py    From kite with GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, model):

        self.components_available = {
            'mean':
            ['Node.mean displacement',
             lambda sp: sp.quadtree.leaf_matrix_means],
            'median':
            ['Node.median displacement',
             lambda sp: sp.quadtree.leaf_matrix_medians],
            'weight':
            ['Node.weight covariance',
             lambda sp: sp.quadtree.leaf_matrix_weights],
        }

        self._component = 'median'

        KitePlot.__init__(self, model=model, los_arrow=True)

        focalpoint_color = (78, 255, 0)
        focalpoint_outline_color = (0, 0, 0)
        self.focal_points = pg.ScatterPlotItem(
            size=3.5,
            pen=pg.mkPen(
                focalpoint_outline_color,
                width=.3),
            brush=pg.mkBrush(focalpoint_color),
            antialias=True)

        self.setMenuEnabled(True)

        self.highlighted_leaves = []
        self.selected_leaves = []
        self.outlined_leaves = None

        self.eraseBox = QtGui.QGraphicsRectItem(0, 0, 1, 1)
        self.eraseBox.setPen(
            pg.mkPen(
                (202, 60, 60),
                width=1,
                style=QtCore.Qt.DotLine))
        self.eraseBox.setBrush(pg.mkBrush(202, 60, 60, 40))
        self.eraseBox.setZValue(1e9)
        self.eraseBox.hide()
        self.addItem(self.eraseBox, ignoreBounds=True)

        self.vb = self.getViewBox()
        self.vb.mouseDragEvent = self.mouseDragEvent
        self.vb.keyPressEvent = self.blacklistSelectedLeaves

        self.addItem(self.focal_points)

        # self.model.sigFrameChanged.connect(self.transFromFrame)
        # self.model.sigFrameChanged.connect(self.transFromFrameScatter) 
Example #21
Source File: test_ScatterPlotItem.py    From tf-pose with Apache License 2.0 4 votes vote down vote up
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())

    # test SymbolAtlas accepts custom symbol
    s = pg.ScatterPlotItem()
    symbol = QtGui.QPainterPath()
    symbol.addEllipse(QtCore.QRectF(-0.5, -0.5, 1, 1))
    s.addPoints([{'pos': [0,0], 'data': 1, 'symbol': symbol}])

    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() 
Example #22
Source File: relativity.py    From tf-pose with Apache License 2.0 4 votes vote down vote up
def getCurve(self, ref=True):
        
        if ref is False:
            data = self.inertData
        else:
            data = self.refData[1:]
            
        x = data['x']
        y = data['t']
        
        curve = pg.PlotCurveItem(x=x, y=y, pen=self.pen)
            #x = self.data['x'] - ref.data['x']
            #y = self.data['t']
        
        step = 1.0
        #mod = self.data['pt'] % step
        #inds = np.argwhere(abs(mod[1:] - mod[:-1]) > step*0.9)
        inds = [0]
        pt = data['pt']
        for i in range(1,len(pt)):
            diff = pt[i] - pt[inds[-1]]
            if abs(diff) >= step:
                inds.append(i)
        inds = np.array(inds)
        
        #t = self.data['t'][inds]
        #x = self.data['x'][inds]   
        pts = []
        for i in inds:
            x = data['x'][i]
            y = data['t'][i]
            if i+1 < len(data):
                dpt = data['pt'][i+1]-data['pt'][i]
                dt = data['t'][i+1]-data['t'][i]
            else:
                dpt = 1
                
            if dpt > 0:
                c = pg.mkBrush((0,0,0))
            else:
                c = pg.mkBrush((200,200,200))
            pts.append({'pos': (x, y), 'brush': c})
            
        points = pg.ScatterPlotItem(pts, pen=self.pen, size=7)
        
        return curve, points 
Example #23
Source File: relativity.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
def getCurve(self, ref=True):
        
        if ref is False:
            data = self.inertData
        else:
            data = self.refData[1:]
            
        x = data['x']
        y = data['t']
        
        curve = pg.PlotCurveItem(x=x, y=y, pen=self.pen)
            #x = self.data['x'] - ref.data['x']
            #y = self.data['t']
        
        step = 1.0
        #mod = self.data['pt'] % step
        #inds = np.argwhere(abs(mod[1:] - mod[:-1]) > step*0.9)
        inds = [0]
        pt = data['pt']
        for i in range(1,len(pt)):
            diff = pt[i] - pt[inds[-1]]
            if abs(diff) >= step:
                inds.append(i)
        inds = np.array(inds)
        
        #t = self.data['t'][inds]
        #x = self.data['x'][inds]   
        pts = []
        for i in inds:
            x = data['x'][i]
            y = data['t'][i]
            if i+1 < len(data):
                dpt = data['pt'][i+1]-data['pt'][i]
                dt = data['t'][i+1]-data['t'][i]
            else:
                dpt = 1
                
            if dpt > 0:
                c = pg.mkBrush((0,0,0))
            else:
                c = pg.mkBrush((200,200,200))
            pts.append({'pos': (x, y), 'brush': c})
            
        points = pg.ScatterPlotItem(pts, pen=self.pen, size=7)
        
        return curve, points 
Example #24
Source File: plotting.py    From pygsp with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _qtg_plot_signal(G, signal, edges, vertex_size, limits, title):

    qtg, gl, QtGui = _import_qtg()

    if G.coords.shape[1] == 2:
        window = qtg.GraphicsWindow(title)
        view = window.addViewBox()

    elif G.coords.shape[1] == 3:
        if not QtGui.QApplication.instance():
            QtGui.QApplication([])  # We want only one application.
        widget = gl.GLViewWidget()
        widget.opts['distance'] = 10
        widget.show()
        widget.setWindowTitle(title)

    if edges:

        if G.coords.shape[1] == 2:
            adj = _get_coords(G, edge_list=True)
            pen = tuple(np.array(G.plotting['edge_color']) * 255)
            g = qtg.GraphItem(pos=G.coords, adj=adj, symbolBrush=None,
                              symbolPen=None, pen=pen)
            view.addItem(g)

        elif G.coords.shape[1] == 3:
            x, y, z = _get_coords(G)
            pos = np.stack((x, y, z), axis=1)
            g = gl.GLLinePlotItem(pos=pos, mode='lines',
                                  color=G.plotting['edge_color'])
            widget.addItem(g)

    pos = [1, 8, 24, 40, 56, 64]
    color = np.array([[0, 0, 143, 255], [0, 0, 255, 255], [0, 255, 255, 255],
                      [255, 255, 0, 255], [255, 0, 0, 255], [128, 0, 0, 255]])
    cmap = qtg.ColorMap(pos, color)

    signal = 1 + 63 * (signal - limits[0]) / limits[1] - limits[0]

    if G.coords.shape[1] == 2:
        gp = qtg.ScatterPlotItem(G.coords[:, 0],
                                 G.coords[:, 1],
                                 size=vertex_size/10,
                                 brush=cmap.map(signal, 'qcolor'))
        view.addItem(gp)

    if G.coords.shape[1] == 3:
        gp = gl.GLScatterPlotItem(pos=G.coords,
                                  size=vertex_size/3,
                                  color=cmap.map(signal, 'float'))
        widget.addItem(gp)

    if G.coords.shape[1] == 2:
        global _qtg_windows
        _qtg_windows.append(window)
    elif G.coords.shape[1] == 3:
        global _qtg_widgets
        _qtg_widgets.append(widget) 
Example #25
Source File: plotting.py    From pygsp with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _plot_spectrogram(G, node_idx):
    r"""Plot the graph's spectrogram.

    Parameters
    ----------
    node_idx : ndarray
        Order to sort the nodes in the spectrogram.
        By default, does not reorder the nodes.

    Notes
    -----
    This function is only implemented for the pyqtgraph backend at the moment.

    Examples
    --------
    >>> G = graphs.Ring(15)
    >>> G.plot_spectrogram()

    """
    from pygsp import features

    qtg, _, _ = _import_qtg()

    if not hasattr(G, 'spectr'):
        features.compute_spectrogram(G)

    M = G.spectr.shape[1]
    spectr = G.spectr[node_idx, :] if node_idx is not None else G.spectr
    spectr = np.ravel(spectr)
    min_spec, max_spec = spectr.min(), spectr.max()

    pos = np.array([0., 0.25, 0.5, 0.75, 1.])
    color = [[20, 133, 212, 255], [53, 42, 135, 255], [48, 174, 170, 255],
             [210, 184, 87, 255], [249, 251, 14, 255]]
    color = np.array(color, dtype=np.ubyte)
    cmap = qtg.ColorMap(pos, color)

    spectr = (spectr.astype(float) - min_spec) / (max_spec - min_spec)

    w = qtg.GraphicsWindow()
    w.setWindowTitle("Spectrogram of {}".format(G.__repr__(limit=4)))
    label = 'frequencies {}:{:.2f}:{:.2f}'.format(0, G.lmax/M, G.lmax)
    v = w.addPlot(labels={'bottom': 'nodes',
                          'left': label})
    v.setAspectLocked()

    spi = qtg.ScatterPlotItem(np.repeat(np.arange(G.N), M),
                              np.ravel(np.tile(np.arange(M), (1, G.N))),
                              pxMode=False,
                              symbol='s',
                              size=1,
                              brush=cmap.map(spectr, 'qcolor'))
    v.addItem(spi)

    global _qtg_windows
    _qtg_windows.append(w)