Python pyqtgraph.TextItem() Examples

The following are 27 code examples of pyqtgraph.TextItem(). 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: __init__.py    From finplot with MIT License 7 votes vote down vote up
def generate_picture(self, bounding_rect):
        rows = self.getrows(bounding_rect)
        if len(rows) > lod_labels: # don't even generate when there's too many of them
            self.clear_items(list(self.text_items.keys()))
            return
        drops = set(self.text_items.keys())
        created = 0
        for x,t,y,txt in rows:
            txt = str(txt)
            key = '%s:%.8f' % (t, y)
            if key in self.text_items:
                item = self.text_items[key]
                item.setText(txt)
                item.setPos(x, y)
                drops.remove(key)
            else:
                self.text_items[key] = item = pg.TextItem(txt, color=self.color, anchor=self.anchor)
                item.setPos(x, y)
                item.setParentItem(self)
                created += 1
        if created > 0 or self.dirty: # only reduce cache if we've added some new or updated
            self.clear_items(drops) 
Example #2
Source File: candle_demo.py    From Python-CTPAPI with MIT License 7 votes vote down vote up
def _init_label(self) -> None:
        """
        Create label objects on axis.
        """
        self._y_labels: Dict[str, pg.TextItem] = {}
        for plot_name, plot in self._plots.items():
            label = pg.TextItem(
                plot_name, fill=CURSOR_COLOR, color=BLACK_COLOR)
            label.hide()
            label.setZValue(2)
            label.setFont(NORMAL_FONT)
            plot.addItem(label, ignoreBounds=True)
            self._y_labels[plot_name] = label

        self._x_label: pg.TextItem = pg.TextItem(
            "datetime", fill=CURSOR_COLOR, color=BLACK_COLOR)
        self._x_label.hide()
        self._x_label.setZValue(2)
        self._x_label.setFont(NORMAL_FONT)
        plot.addItem(self._x_label, ignoreBounds=True) 
Example #3
Source File: waveformwidget.py    From dunya-desktop with GNU General Public License v3.0 6 votes vote down vote up
def __add_items_to_plot(self, len_plot, min_audio, max_audio):
        """
        Adds a region selector item and vertical line for to the waveform plot.

        :param len_plot: (int) Number of samples in plotted waveform array.
        :param min_audio: (float) The minimum value of plotted waveform array.
        :param max_audio: (float) The maximum value of plotted waveform array.
        """

        # Create a waveform region item and add it to waveform plot
        pos_wf_x_max = len_plot * 0.05  # Region item focuses on the 5% of
        # waveform plot.
        self.region_wf = WaveformRegionItem(values=[0, pos_wf_x_max],
                                            brush=WAVEFORM_BRUSH,
                                            bounds=[0., len_plot])

        # Creating a cursor with pyqtgraph.ROI
        self.vline_wf = pg.ROI(pos=[0, min_audio],
                               size=[0, max_audio - min_audio],
                               angle=0, pen=WAVEFORM_VLINE)

        # add items to waveform plot
        self.waveform.addItem(self.region_wf)
        self.waveform.addItem(self.vline_wf)

        # text item
        self.section_label = pg.TextItem(text='')
        self.waveform.addItem(self.section_label) 
Example #4
Source File: go.py    From diyECG-1opAmp with MIT License 6 votes vote down vote up
def __init__(self, parent=None):
        pyqtgraph.setConfigOption('background', 'w') #before loading widget
        super(ExampleApp, self).__init__(parent)
        self.setupUi(self)
        self.grECG.plotItem.showGrid(True, True, 0.7)
        self.btnSave.clicked.connect(self.saveFig)
        self.btnSite.clicked.connect(self.website)
        stamp="DIY ECG by Scott Harden"
        self.stamp = pyqtgraph.TextItem(stamp,anchor=(-.01,1),color=(150,150,150),
                                        fill=pyqtgraph.mkBrush('w'))
        self.ear = swhear.Ear(chunk=int(100)) # determines refresh rate
        # optionally you can manually set the audio input device to use like this:
        # self.ear = swhear.Ear(chunk=int(100), device=5) # use audio input device 5
        if len(self.ear.valid_input_devices()):
            self.ear.stream_start()
            self.lblDevice.setText(self.ear.msg)
            self.update() 
Example #5
Source File: candle_demo.py    From Python-CTPAPI with MIT License 6 votes vote down vote up
def _init_info(self) -> None:
        """
        """
        self._infos: Dict[str, pg.TextItem] = {}
        for plot_name, plot in self._plots.items():
            info = pg.TextItem(
                "info",
                color=CURSOR_COLOR,
                border=CURSOR_COLOR,
                fill=BLACK_COLOR
            )
            info.hide()
            info.setZValue(2)
            info.setFont(NORMAL_FONT)
            plot.addItem(info)  # , ignoreBounds=True)
            self._infos[plot_name] = info 
Example #6
Source File: uiCrosshair.py    From InplusTrader_Linux with MIT License 6 votes vote down vote up
def __init__(self,parent):
        """Constructor"""
        self.__view = parent
        
        super(Crosshair, self).__init__()
        self.__vLine = pg.InfiniteLine(angle=90, movable=False)
        self.__hLine = pg.InfiniteLine(angle=0, movable=False)
        self.__textPrice = pg.TextItem('price')
        self.__textDate = pg.TextItem('date')
        
        #mid 在y轴动态跟随最新价显示最新价和最新时间
        self.__textLastPrice = pg.TextItem('lastTickPrice')    
        
        view = self.__view
        
        view.addItem(self.__textDate, ignoreBounds=True)
        view.addItem(self.__textPrice, ignoreBounds=True)        
        view.addItem(self.__vLine, ignoreBounds=True)
        view.addItem(self.__hLine, ignoreBounds=True)    
        view.addItem(self.__textLastPrice, ignoreBounds=True)     
        self.proxy = pg.SignalProxy(view.scene().sigMouseMoved, rateLimit=60, slot=self.__mouseMoved)        
        
    #---------------------------------------------------------------------- 
Example #7
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 #8
Source File: locopositioning_tab.py    From crazyflie-clients-python with GNU General Public License v2.0 5 votes vote down vote up
def _plot_anchor(self, x, y, anchor_id, distance, display_mode, is_active):
        if is_active:
            brush = PlotWrapper.ANCHOR_BRUSH
        else:
            brush = PlotWrapper.ANCHOR_BRUSH_INVALID

        size = PlotWrapper.ANCHOR_SIZE
        font_size = self.LABEL_SIZE
        if display_mode is DisplayMode.identify_anchor:
            if distance < PlotWrapper.VICINITY_DISTANCE:
                brush = self._mix_brushes(
                    brush,
                    PlotWrapper.HIGHLIGHT_ANCHOR_BRUSH,
                    distance / PlotWrapper.VICINITY_DISTANCE)

            if distance < PlotWrapper.HIGHLIGHT_DISTANCE:
                brush = PlotWrapper.HIGHLIGHT_ANCHOR_BRUSH
                size = PlotWrapper.HIGHLIGHT_SIZE
                font_size = self.LABEL_HIGHLIGHT_SIZE

        self.widget.plot([x], [y], pen=None, symbolBrush=brush,
                         symbolSize=size)

        text = pg.TextItem(text="{}".format(anchor_id))
        font = QFont("Helvetica", font_size)
        text.setFont(font)
        self.widget.addItem(text)
        text.setPos(x, y) 
Example #9
Source File: CustomGraphItem.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def setTexts(self, text):
        for i in self.textItems:
            i.scene().removeItem(i)
        self.textItems = []
        for t in text:
            item = pg.TextItem(t)
            self.textItems.append(item)
            item.setParentItem(self) 
Example #10
Source File: __init__.py    From finplot with MIT License 5 votes vote down vote up
def add_text(pos, s, color=draw_line_color, anchor=(0,0), ax=None):
    ax = _create_plot(ax=ax, maximize=False)
    text = pg.TextItem(s, color=color, anchor=anchor)
    text.setPos(_pdtime2index(ax, pd.Series([pos[0]]))[0], pos[1])
    text.setZValue(50)
    text.ax = ax
    ax.addItem(text, ignoreBounds=True)
    return text 
Example #11
Source File: __init__.py    From finplot with MIT License 5 votes vote down vote up
def addSegment(self, h1, h2, index=None):
        super().addSegment(h1, h2, index)
        text = pg.TextItem(color=draw_line_color)
        text.setZValue(50)
        text.segment = self.segments[-1 if index is None else index]
        if index is None:
            self.texts.append(text)
        else:
            self.texts.insert(index, text)
        self.update_text(text)
        self.vb.addItem(text, ignoreBounds=True) 
Example #12
Source File: __init__.py    From finplot with MIT License 5 votes vote down vote up
def __init__(self, ax, color):
        self.ax = ax
        self.x = 0
        self.y = 0
        self.clamp_x = 0
        self.clamp_y = 0
        self.infos = []
        pen = pg.mkPen(color=color, style=QtCore.Qt.CustomDashLine, dash=[7, 7])
        self.vline = pg.InfiniteLine(angle=90, movable=False, pen=pen)
        self.hline = pg.InfiniteLine(angle=0, movable=False, pen=pen)
        self.xtext = pg.TextItem(color=color, anchor=(0,1))
        self.ytext = pg.TextItem(color=color, anchor=(0,0))
        self.vline.setZValue(50)
        self.hline.setZValue(50)
        self.xtext.setZValue(50)
        self.ytext.setZValue(50)
        ax.addItem(self.vline, ignoreBounds=True)
        ax.addItem(self.hline, ignoreBounds=True)
        ax.addItem(self.xtext, ignoreBounds=True)
        ax.addItem(self.ytext, ignoreBounds=True) 
Example #13
Source File: mouseFlow.py    From PyQt with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)
        self.setupUi(self)
        x = np.linspace(-100, 100, 1000)
        data = np.sin(x) / x
        self.graphicsView.plot(data, pen=(255, 255, 255, 200))
        self.label = pg.TextItem(text="横坐标:{}".format(0))
        self.graphicsView.addItem(self.label)
        self.setMouseTracking(True)
        self.graphicsView.scene().sigMouseMoved.connect(self.onMouseMoved) 
Example #14
Source File: similarity.py    From tridesclous with MIT License 5 votes vote down vote up
def refresh(self):
        if self.similarity is None:
            self.image.hide()
            return
        
        _max = np.max(self.similarity)

        s = self.similarity
        #~ _max = np.max(s)
        _max = 1
        
        self.image.setImage(s, lut=self.lut, levels=[0, _max])
        self.image.show()
        self.plot.setXRange(0, s.shape[0])
        self.plot.setYRange(0, s.shape[1])

        for item in self._text_items:
            self.plot.removeItem(item)
        
        for pos, k in enumerate(self.controller.positive_cluster_labels):
            for i in range(2):
                item = pg.TextItem(text='{}'.format(k), color='#FFFFFF', anchor=(0.5, 0.5), border=None)
                self.plot.addItem(item)
                if i==0:
                    item.setPos(pos+0.5, 0)
                else:
                    item.setPos(0, pos+0.5)
                self._text_items.append(item) 
Example #15
Source File: similarity.py    From tridesclous with MIT License 5 votes vote down vote up
def refresh(self):
        if self.similarity is None:
            self.image.hide()
            return
        
        _max = np.max(self.similarity)
        
        cluster_visible = self.controller.cluster_visible
        visibles = [c for c, v in self.controller.cluster_visible.items() if v and c>=0]
        
        labels = self.controller.spike_label[self.controller.some_peaks_index]
        keep_ind,  = np.nonzero(np.in1d(labels, visibles))
        keep_label = labels[keep_ind]
        order = np.argsort(keep_label)
        keep_ind = keep_ind[order]
        
        if keep_ind.size>0:
            s = self.similarity[keep_ind,:][:, keep_ind]
            self.image.setImage(s, lut=self.lut, levels=[0, _max])
            self.image.show()
            self.plot.setXRange(0, s.shape[0])
            self.plot.setYRange(0, s.shape[1])
            
            for item in self._text_items:
                self.plot.removeItem(item)
            
            pos = 0
            for k in np.sort(visibles):
                n = np.sum(keep_label==k)
                for i in range(2):
                    item = pg.TextItem(text='{}'.format(k), color='#FFFFFF', anchor=(0.5, 0.5), border=None)
                    self.plot.addItem(item)
                    if i==0:
                        item.setPos(pos+n/2., 0)
                    else:
                        item.setPos(0, pos+n/2.)
                    self._text_items.append(item)
                pos += n
                
        else:
            self.image.hide() 
Example #16
Source File: probegeometryview.py    From tridesclous with MIT License 5 votes vote down vote up
def refresh(self, v=None):
        self.plot.clear()
        
        flip_bottom_up = self.checkbox.checkState()
        
        
        chan_grp = int(self.combo_chan_grp.currentText())
        channel_group = self.channel_groups[chan_grp]
        if channel_group['geometry'] is None:
            return
        
        
        geometry = [ channel_group['geometry'][chan] for chan in channel_group['channels'] ]
        geometry = np.array(geometry, dtype='float64')
        
        if flip_bottom_up:
            geometry[:, 1] *= -1.
        
        for c, chan in enumerate(channel_group['channels']):
            x, y = geometry[c]
            
            #~ name = '{}: {}'.format(c, chan)
            name = '{}'.format(chan)
            itemtxt = pg.TextItem(name, anchor=(.5,.5))
            self.plot.addItem(itemtxt)
            itemtxt.setPos(x, y)

        margin = 100
        
        self.plot.setXRange(np.min(geometry[:, 0])-margin, np.max(geometry[:, 0])+margin)
        self.plot.setYRange(np.min(geometry[:, 1])-margin, np.max(geometry[:, 1])+margin)
            

    #~ for c, chan in enumerate(channels):
        #~ x, y = geometry[c]
        #~ ax.plot([x], [y], marker='o', color='r')
        #~ ax.text(x, y, '{}: {}'.format(c, chan),  size=20) 
Example #17
Source File: qtGraph.py    From simulator with GNU General Public License v3.0 5 votes vote down vote up
def setTexts(self, text):
        for i in self.textItems:
            i.scene().removeItem(i)
        self.textItems = []
        for t in text:
            item = pg.TextItem(t)
            self.textItems.append(item)
            item.setParentItem(self) 
Example #18
Source File: CustomGraphItem.py    From tf-pose with Apache License 2.0 5 votes vote down vote up
def setTexts(self, text):
        for i in self.textItems:
            i.scene().removeItem(i)
        self.textItems = []
        for t in text:
            item = pg.TextItem(t)
            self.textItems.append(item)
            item.setParentItem(self) 
Example #19
Source File: uiCrosshair.py    From uiKLine with MIT License 4 votes vote down vote up
def __init__(self,parent,master):
        """Constructor"""
        self.__view = parent
        self.master = master
        super(Crosshair, self).__init__()

        self.xAxis = 0
        self.yAxis = 0

        self.datas = None
        self.ma_s_values = []
        self.ma_l_values = []

        self.yAxises    = [0 for i in range(3)]
        self.leftX      = [0 for i in range(3)]
        self.showHLine  = [False for i in range(3)]
        self.textPrices = [pg.TextItem('',anchor=(1,1)) for i in range(3)]
        self.views      = [parent.centralWidget.getItem(i+1,0) for i in range(3)]
        self.rects      = [self.views[i].sceneBoundingRect() for i in range(3)]
        self.vLines     = [pg.InfiniteLine(angle=90, movable=False) for i in range(3)]
        self.hLines     = [pg.InfiniteLine(angle=0,  movable=False) for i in range(3)]
        
        #mid 在y轴动态跟随最新价显示最新价和最新时间
        self.__textDate   = pg.TextItem('date',anchor=(1,1))
        self.__textInfo   = pg.TextItem('lastBarInfo')   
        self.__textSig    = pg.TextItem('lastSigInfo',anchor=(1,0))   
        self.__textSubSig = pg.TextItem('lastSubSigInfo',anchor=(1,0))   
        self.__textVolume = pg.TextItem('lastBarVolume',anchor=(1,0))   

        self.__textDate.setZValue(2)
        self.__textInfo.setZValue(2)
        self.__textSig.setZValue(2)
        self.__textSubSig.setZValue(2)
        self.__textVolume.setZValue(2)
        self.__textInfo.border = pg.mkPen(color=(230, 255, 0, 255), width=1)
        
        for i in range(3):
            self.textPrices[i].setZValue(2)
            self.vLines[i].setPos(0)
            self.hLines[i].setPos(0)
            self.vLines[i].setZValue(0)
            self.hLines[i].setZValue(0)
            self.views[i].addItem(self.vLines[i])
            self.views[i].addItem(self.hLines[i])
            self.views[i].addItem(self.textPrices[i])
        
        self.views[0].addItem(self.__textInfo, ignoreBounds=True)     
        self.views[0].addItem(self.__textSig, ignoreBounds=True)     
        self.views[1].addItem(self.__textVolume, ignoreBounds=True)     
        self.views[2].addItem(self.__textDate, ignoreBounds=True)
        self.views[2].addItem(self.__textSubSig, ignoreBounds=True)     
        self.proxy = pg.SignalProxy(self.__view.scene().sigMouseMoved, rateLimit=360, slot=self.__mouseMoved)        
        # 跨线程刷新界面支持
        self.signal.connect(self.update)
        self.signalInfo.connect(self.plotInfo)

    #---------------------------------------------------------------------- 
Example #20
Source File: uiCrosshair.py    From uiKLine with MIT License 4 votes vote down vote up
def __init__(self,parent,master):
        """Constructor"""
        self.__view = parent
        self.master = master
        super(Crosshair, self).__init__()

        self.xAxis = 0
        self.yAxis = 0

        self.datas = None

        self.yAxises    = [0 for i in range(3)]
        self.leftX      = [0 for i in range(3)]
        self.showHLine  = [False for i in range(3)]
        self.textPrices = [pg.TextItem('',anchor=(1,1)) for i in range(3)]
        self.views      = [parent.centralWidget.getItem(i+1,0) for i in range(3)]
        self.rects      = [self.views[i].sceneBoundingRect() for i in range(3)]
        self.vLines     = [pg.InfiniteLine(angle=90, movable=False) for i in range(3)]
        self.hLines     = [pg.InfiniteLine(angle=0,  movable=False) for i in range(3)]
        
        #mid 在y轴动态跟随最新价显示最新价和最新时间
        self.__textDate   = pg.TextItem('date',anchor=(1,1))
        self.__textInfo   = pg.TextItem('lastBarInfo')   
        self.__textSig    = pg.TextItem('lastSigInfo',anchor=(1,0))   
        self.__textSubSig = pg.TextItem('lastSubSigInfo',anchor=(1,0))   
        self.__textVolume = pg.TextItem('lastBarVolume',anchor=(1,0))   

        self.__textDate.setZValue(2)
        self.__textInfo.setZValue(2)
        self.__textSig.setZValue(2)
        self.__textSubSig.setZValue(2)
        self.__textVolume.setZValue(2)
        self.__textInfo.border = pg.mkPen(color=(230, 255, 0, 255), width=1.2)
        
        for i in range(3):
            self.textPrices[i].setZValue(2)
            self.vLines[i].setPos(0)
            self.hLines[i].setPos(0)
            self.vLines[i].setZValue(0)
            self.hLines[i].setZValue(0)
            self.views[i].addItem(self.vLines[i])
            self.views[i].addItem(self.hLines[i])
            self.views[i].addItem(self.textPrices[i])
        
        self.views[0].addItem(self.__textInfo, ignoreBounds=True)     
        self.views[0].addItem(self.__textSig, ignoreBounds=True)     
        self.views[1].addItem(self.__textVolume, ignoreBounds=True)     
        self.views[2].addItem(self.__textDate, ignoreBounds=True)
        self.views[2].addItem(self.__textSubSig, ignoreBounds=True)     
        self.proxy = pg.SignalProxy(self.__view.scene().sigMouseMoved, rateLimit=360, slot=self.__mouseMoved)        
        # 跨线程刷新界面支持
        self.signal.connect(self.update)
        self.signalInfo.connect(self.plotInfo)

    #---------------------------------------------------------------------- 
Example #21
Source File: silhouette.py    From tridesclous with MIT License 4 votes vote down vote up
def refresh(self):
        self.plot.clear()
        silhouette_values = self.controller.spike_silhouette
        if silhouette_values is None:
            return
        
        if silhouette_values.shape != self.controller.spike_label.shape:
            return
        
        silhouette_avg = np.mean(silhouette_values)
        silhouette_by_labels = {}
        labels = self.controller.spike_label
        labels_list = np.unique(labels)
        for k in labels_list:
            v = silhouette_values[k==labels]
            v.sort()
            silhouette_by_labels[k] = v
        
        
        self.vline = pg.InfiniteLine(pos=silhouette_avg, angle = 90, movable = False, pen = '#FF0000')
        self.plot.addItem(self.vline)
        
        y_lower = 10
        cluster_visible = self.controller.cluster_visible
        visibles = [c for c, v in self.controller.cluster_visible.items() if v and c>=0]
        
        for k in visibles:
            if k not in silhouette_by_labels:
                continue
            v = silhouette_by_labels[k]
            
            color = self.controller.qcolors[k]
            color2 = QT.QColor(color)
            color2.setAlpha(self.alpha)
            
            y_upper = y_lower + v.size
            y_vect = np.arange(y_lower, y_upper)
            curve1 = pg.PlotCurveItem(np.zeros(v.size), y_vect, pen=color)
            curve2 = pg.PlotCurveItem(v, y_vect, pen=color)
            self.plot.addItem(curve1)
            self.plot.addItem(curve2)
            fill = pg.FillBetweenItem(curve1=curve1, curve2=curve2, brush=color2)
            self.plot.addItem(fill)
            
            txt = pg.TextItem( text='{}'.format(k), color='#FFFFFF', anchor=(0, 0.5), border=None)#, fill=pg.mkColor((128,128,128, 180)))
            self.plot.addItem(txt)
            txt.setPos(0, (y_upper+y_lower)/2.)
            
            y_lower = y_upper + 10

        
        self.plot.setXRange(-.5, 1.)
        self.plot.setYRange(0,y_lower) 
Example #22
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 #23
Source File: crosshair.py    From equant with GNU General Public License v2.0 4 votes vote down vote up
def __init__(self, parent, master):
        """Constructor"""
        self.__view = parent
        self.master = master
        super(Crosshair, self).__init__()

        self.xAxis = 0
        self.yAxis = 0

        # 文字信息是否显示标志位
        self.flags = False

        self.datas = None

        self.yAxises = 0
        self.leftX = 0
        self.showHLine = False
        self.textPrices = pg.TextItem('', anchor=(1, 1))
        self.view = parent.centralWidget.getItem(1, 0)
        self.rect = self.view.sceneBoundingRect()
        self.vLines = pg.InfiniteLine(angle=90, movable=False)
        self.hLines = pg.InfiniteLine(angle=0, movable=False)

        # mid 在y轴动态跟随最新价显示资金信息和最新时间
        self.__textDate = pg.TextItem('date')
        self.__textInfo = pg.TextItem('lastBarInfo')

        self.__textDate.setZValue(2)
        # 堆叠顺序置于下层
        self.__textInfo.setZValue(-1)
        self.__textInfo.border = pg.mkPen(color=(181, 181, 181, 255), width=1.2)

        self.__texts = [self.__textDate, self.__textInfo, self.textPrices]

        self.textPrices.setZValue(2)
        self.vLines.setPos(0)
        self.hLines.setPos(0)
        self.view.addItem(self.vLines)
        self.view.addItem(self.hLines)
        self.view.addItem(self.textPrices)

        self.view.addItem(self.__textInfo, ignoreBounds=True)
        self.view.addItem(self.__textDate, ignoreBounds=True)

        self.__setVisibileOrNot(self.flags)

        self.proxy = pg.SignalProxy(self.__view.scene().sigMouseMoved, rateLimit=60, slot=self.__mouseMoved)
        self.click_slot = pg.SignalProxy(self.__view.scene().sigMouseClicked, rateLimit=60, slot=self.__mouseClicked)
        # 跨线程刷新界面支持
        self.signal.connect(self.update) 
Example #24
Source File: graphtab.py    From equant with GNU General Public License v2.0 4 votes vote down vote up
def __init__(self, parent, master):
        """Constructor"""
        self.__view = parent
        self.master = master
        super(GCrosshair, self).__init__()

        self.xAxis = 0
        self.yAxis = 0

        # 文字信息是否显示标志位
        self.flags = False

        self.datas = None

        self.yAxises = 0
        self.leftX = 0
        self.showHLine = False

        self.view = parent.centralWidget.getItem(1, 0)
        self.rect = self.view.sceneBoundingRect()
        self.vLines = pg.InfiniteLine(angle=90, movable=False)
        self.hLines = pg.InfiniteLine(angle=0, movable=False)

        # mid 在y轴动态跟随最新价显示资金信息和最新时间
        self.__textInfo = pg.TextItem('lastBarInfo')

        # 堆叠顺序置于下层
        self.__textInfo.setZValue(1)
        self.__textInfo.border = pg.mkPen(color=(181, 181, 181, 255), width=1.2)

        self.__texts = [self.__textInfo]

        self.vLines.setPos(0)
        self.hLines.setPos(0)
        self.view.addItem(self.vLines)
        self.view.addItem(self.hLines)

        self.view.addItem(self.__textInfo, ignoreBounds=True)

        self.__setVisibileOrNot(self.flags)

        self.proxy = pg.SignalProxy(self.__view.scene().sigMouseMoved, rateLimit=60, slot=self.__mouseMoved)
        self.click_slot = pg.SignalProxy(self.__view.scene().sigMouseClicked, rateLimit=60, slot=self.__mouseClicked)
        # 跨线程刷新界面支持
        self.signal.connect(self.update) 
Example #25
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 #26
Source File: play.py    From simulator with GNU General Public License v3.0 4 votes vote down vote up
def update_buffer(self, node, senders_shot):

        if self.buffer_order.get(node) is None:
            self.buffer_order[node] = self.buffer_index
            self.buffer_labels.append(node)
            text = pg.TextItem()
            text.setText("P"+str(self.buffer_index))
            text.setColor(self.QColors[self.buffer_index])
            text.setFont(QtGui.QFont("arial", 16))
            text.setPos(self.buffer_index, 1)
            self.p4.addItem(text)   # Add label for newly added peer
            self.buffer_index += 1

        senders_list = senders_shot.split(":")
        buffer_order_node = self.buffer_order[node]
        self.OutData[buffer_order_node].clear()

        for pos, sender in enumerate(senders_list):
            self.clear_all((buffer_order_node, pos))  # Clear previous color point, to avoid overapping
            if sender != "":
                ix = self.buffer_order[sender]
                self.Data[ix].add((buffer_order_node, pos))
            else:
                self.OutData[buffer_order_node].add((buffer_order_node, pos))

        ######
        xIn = []
        yIn = []
        for i in range(self.total_peers):
            tempData = list(self.Data[i])
            xIn.append([])
            yIn.append([])
            for pt in tempData:
                xIn[i].append(pt[0])
                yIn[i].append(pt[1])

        xOut = []
        yOut = []
        for i in range(self.total_peers):
            tempData = list(self.OutData[i])
            for pt in tempData:
                xOut.append(pt[0])
                yOut.append(pt[1])
        ######

        self.lineOUT.setData(x=xOut, y=yOut)
        for ix in range(self.total_peers):
            self.lineIN[ix].setData(x=xIn[ix], y=yIn[ix]) 
Example #27
Source File: uiKLine.py    From vnpy_crypto with MIT License 4 votes vote down vote up
def add_markup(self, t_value,price, txt):
        """
        添加标记
        :param t_value: 时间-》坐标x
        :param price: 坐标y
        :param txt: 文字
        :return:
        """
        # 找到信号时间最贴近的bar x轴
        x = self.axisTime.get_x_by_time(t_value)

        # 修正一下 标记时间,改为bar的时间
        if x not in self.x_t_markup_map:
            bar_time = self.axisTime.xdict.get(x, t_value)
        else:
            # 如果存在映射,就更新
            bar_time = self.x_t_markup_map[x]

        markup_node = self.t_markup_dict.get(bar_time, None)
        if markup_node is None:
            # 当前时间无标记
            markup_node = {'x': x, 'markup': [txt]}
            self.t_markup_dict[bar_time] = markup_node
            self.x_t_markup_map[x] = bar_time
        else:
            if '.' in txt:
                txt_list = txt.split('.')
            else:
                txt_list = [txt]

            for t in txt_list:
                if t in markup_node['markup']:
                    continue
                markup_node['markup'].append(t)

        if 'textitem' in markup_node:
            markup_node['textitem'].setText(';'.join(markup_node.get('markup',[])))
        else:
            textitem = pg.TextItem(markup_node['markup'][0])
            textitem.setPos(x,price)
            markup_node['textitem'] = textitem
            self.list_markup.append(textitem)
            self.pi_main.addItem(textitem)