def __init__(self):

        # pyqtgraph stuff
        pg.setConfigOptions(antialias=True)
        self.traces = dict()
        self.app = QtGui.QApplication(sys.argv)
        self.win = pg.GraphicsWindow(title='Spectrum Analyzer')
        self.win.setWindowTitle('Spectrum Analyzer')
        self.win.setGeometry(5, 115, 1200, 600)
        # self.win.

        wf_xlabels = [(0, '0'), (2048, '2048'), (4096, '4096')]
        wf_xaxis = pg.AxisItem(orientation='bottom')
        wf_xaxis.setTicks([wf_xlabels])

        wf_ylabels = [(0, '0'), (127, '128'), (255, '255')]
        wf_yaxis = pg.AxisItem(orientation='left')
        wf_yaxis.setTicks([wf_ylabels])

        sp_xlabels = [
            (np.log10(10), '10'), (np.log10(100), '100'),
            (np.log10(1000), '1000'), (np.log10(22050), '22050')
        ]
        sp_xaxis = pg.AxisItem(orientation='bottom')
        sp_xaxis.setTicks([sp_xlabels])

        self.waveform = self.win.addPlot(
            title='WAVEFORM', row=1, col=1, axisItems={'bottom': wf_xaxis, 'left': wf_yaxis},
        )
        self.spectrum = self.win.addPlot(
            title='SPECTRUM', row=2, col=1,
        )

        # pyaudio stuff
        self.FORMAT = pyaudio.paInt16
        self.CHANNELS = 1
        self.RATE = 44100
        self.CHUNK = 1024 * 2

        self.p = pyaudio.PyAudio()
        self.stream = self.p.open(
            format=self.FORMAT,
            channels=self.CHANNELS,
            rate=self.RATE,
            input=True,
            output=True,
            frames_per_buffer=self.CHUNK,
        )
        # waveform and spectrum x points
        self.x = np.arange(0, 2 * self.CHUNK, 2)
        self.f = np.linspace(0, self.RATE / 2, self.CHUNK // 2)
Beispiel #2
0
    def __init__(self):

        # How many samples per second
        self.RATE = 384000
        # How many bytes are read for each frame
        self.CHUNK = int(4096)
        self.scale = 4
        self.stream = open("usrp_samples.dat", "rb")
        pg.setConfigOptions(antialias=True, useOpenGL=True)
        self.traces = dict()
        self.app = QtGui.QApplication(sys.argv)
        self.win = pg.GraphicsWindow(title='Spectrum Analyzer')
        self.win.setWindowTitle('Spectrum Analyzer')
        self.win.setGeometry(160, 90, 1600, 900)
        wf_xlabels = [(0, '0'), (2048, '2048'), (4096, '4096'), (8192, '8192'),
                      (16384, '16384')]
        wf_xaxis = pg.AxisItem(orientation='bottom')
        wf_xaxis.setTicks([wf_xlabels])

        wf_ylabels = [(0, '0'), (127, '128'), (255, '255')]
        wf_yaxis = pg.AxisItem(orientation='left')
        wf_yaxis.setTicks([wf_ylabels])

        self.waveform = self.win.addPlot(
            title='WAVEFORM',
            row=1,
            col=1,
            axisItems={
                'bottom': wf_xaxis,
                'left': wf_yaxis
            },
        )

        sp_xlabels = [(np.log10(1), '1'), (np.log10(10), '10'),
                      (np.log10(100), '100'), (np.log10(1000), '1000'),
                      (np.log10(10000), '10000'), (np.log10(100000), '100000'),
                      (np.log10(1000000), '1000000'),
                      (np.log10(10000000), '10000000')]
        sp_xaxis = pg.AxisItem(orientation='bottom')
        sp_xaxis.setTicks([sp_xlabels])

        self.spectrum = self.win.addPlot(
            title='SPECTRUM',
            row=2,
            col=1,
            axisItems={'bottom': sp_xaxis},
        )

        self.x = np.arange(0, 2 * self.CHUNK / self.scale, 2)
        self.f = np.linspace(0, self.RATE / 2, self.CHUNK / self.scale)
    def __init__(self, title, label=None, color='w', offset=0, parent=None):
        super().__init__(parent)
        self.title = title

        self.offset = offset

        self.Abs = np.array([])
        self.Ord = np.array([])
        self.ax_y = pg.AxisItem('left', pen=pg.mkPen('w', width=2))
        self.ax_x = pg.AxisItem('bottom', pen=pg.mkPen('w', width=2))

        self.ax_x.tickFont = fontTicks
        self.ax_y.tickFont = fontTicks

        # self.ax_x.tickTextOffset = 32
        # self.ax_y.tickTextOffset = 32
        # self.ax_x.tickTextHeight = 32
        # self.ax_y.tickTextheight = 32

        labelStyle = {'color': '#FFF', 'font-size': '12pt'}

        self.ax_x.setLabel('Time (s)', **labelStyle)
        self.ax_y.setLabel(label + '(mm)', **labelStyle)

        self.ax_x.showLabel(True)
        self.ax_y.showLabel(True)

        self.plot1 = self.addPlot(title=title,
                                  pen=pg.mkPen(color, width=2),
                                  axisItems={
                                      'left': self.ax_y,
                                      'bottom': self.ax_x
                                  })

        self.curve = self.plot1.plot(self.Abs,
                                     self.Ord,
                                     pen=pg.mkPen(color, width=3))
        self.curve.setClipToView(True)

        self.plot1.enableAutoRange('xy', True)
        self.plot1.showGrid(x=True, y=True)

        self.point = QtCore.QPointF(0, 0)
        self.vLine = pg.InfiniteLine(pos=self.point,
                                     angle=90,
                                     movable=False,
                                     pen=pg.mkPen('r', width=3))

        self.plot1.addItem(self.vLine, ignoreBounds=True)
Beispiel #4
0
    def initUI(self):
        win = pg.GraphicsLayoutWidget()
        win.resize(1000, 600)
        win.setWindowTitle(u"Node: " + unicode(self.parent().name()))

        # Enable anti-aliasing for prettier plots
        pg.setConfigOptions(antialias=True)
        # Add Label where coords of current mouse position will be printed
        self.coordLabel = pg.LabelItem(justify='right')
        win.addItem(self.coordLabel)

        #add custom datetime axis
        x_axis1 = DateAxisItem(orientation='bottom')
        x_axis2 = DateAxisItem(orientation='bottom')
        self.y_axis1 = pg.AxisItem(
            orientation='left'
        )  # keep reference to itm since we want to modify its label
        self.y_axis2 = pg.AxisItem(
            orientation='left'
        )  # keep reference to itm since we want to modify its label

        self.p1 = win.addPlot(row=1,
                              col=0,
                              axisItems={
                                  'bottom': x_axis1,
                                  'left': self.y_axis1
                              })
        #self.p1.setClipToView(True)
        self.p2 = win.addPlot(row=2,
                              col=0,
                              axisItems={
                                  'bottom': x_axis2,
                                  'left': self.y_axis2
                              },
                              enableMenu=False,
                              title=' ')
        #self.p1.setClipToView(True)
        self.vb = self.p1.vb  # ViewBox

        self.zoomRegion = pg.LinearRegionItem()
        self.zoomRegion.setZValue(-10)
        self.zoomRegion.setRegion([1000, 2000])
        self.p2.addItem(self.zoomRegion, ignoreBounds=True)

        self.p1.setAutoVisible(y=True)
        self.legend = self.p1.addLegend()

        self.initCrosshair()
        self.win = win
Beispiel #5
0
def test_PlotItem_shared_axis_items(orientation):
    """Adding an AxisItem to multiple plots raises RuntimeError"""
    ax1 = pg.AxisItem(orientation)
    ax2 = pg.AxisItem(orientation)

    layout = pg.GraphicsLayoutWidget()

    _ = layout.addPlot(axisItems={orientation: ax1})

    pi2 = layout.addPlot()
    # left or bottom replaces, right or top adds new
    pi2.setAxisItems({orientation: ax2})

    with pytest.raises(RuntimeError):
        pi2.setAxisItems({orientation: ax1})
def test_AxisItem_label_visibility():
    """Test the visibility of the axis item using `setLabel`"""
    axis = pg.AxisItem('left')
    assert axis.labelText == ''
    assert axis.labelUnits == ''
    assert not axis.label.isVisible()
    axis.setLabel(text='Position', units='mm')
    assert axis.labelText == 'Position'
    assert axis.labelUnits == 'mm'
    assert axis.label.isVisible()
    # XXX: `None` is converted to empty strings.
    axis.setLabel(text=None, units=None)
    assert axis.labelText == ''
    assert axis.labelUnits == ''
    assert not axis.label.isVisible()
    axis.setLabel(text='Current', units=None)
    assert axis.labelText == 'Current'
    assert axis.labelUnits == ''
    assert axis.label.isVisible()
    axis.setLabel(text=None, units=None)
    assert not axis.label.isVisible()
    axis.setLabel(text='', units='V')
    assert axis.labelText == ''
    assert axis.labelUnits == 'V'
    assert axis.label.isVisible()
Beispiel #7
0
    def __init__(self, parent, path, relevant_stage_dict):
        super().__init__()
        self.filters = np.load(path)
        self.parent = parent
        self.grid_layout = QGridLayout()
        self.ax_list = []
        self.ncols = 8
        self.nrows = 8
        self.peaks = True
        self.relevant_stage_dict = relevant_stage_dict

        for i in range(self.ncols):
            for j in range(self.nrows):
                y_axis = pg.AxisItem(orientation='left')
                y_axis.setTicks([[(0, '0'), (1, '1'), (2, '2')]])
                ax = MyPlotWidget(self, idx=i * self.nrows + j)
                ax.setBackground('w')
                view = ax.addViewBox(row=0, col=0)
                self.grid_layout.addWidget(ax, i, j, 1, 1)
                self.ax_list.append(ax)

                # plot_on_ax = ax.addPlot(row=0, col=0)
                item = pg.PlotDataItem(x=np.arange(self.filters.shape[2]),
                                       y=self.filters[i * self.nrows +
                                                      j].squeeze(),
                                       pen=pg.mkPen(color='b', width=0.3))
                # plot_on_ax.addItem(item)
                # plot_on_ax.setYRange(-50, 50)
                view.setRange(yRange=(-40, 40))
                # item.addItem(y_axis)
                view.addItem(item)
                ax.set_item(item)

        self.setLayout(self.grid_layout)
Beispiel #8
0
    def draw_timebar(self):
        # --------------删除以前的内容
        for w in self.timebar_d1.widgets:
            self.timebar_d1.layout.removeWidget(w)
        for w in self.timebar_d2.widgets:
            self.timebar_d2.layout.removeWidget(w)
        # -----------------重新画
        df = self.db.get_ticks(self.code)
        if df.empty:
            return
        self.timebar_t = dt_cal(df.datetime)
        self.timebar_p = df.price.to_list()
        self.timebar_v = df.vol.to_list()

        strings = ['09:30', '10:00', '10:30', '11:00', '11:30', '13:30', '14:00', '14:30', '15:00']
        temp = time.strftime('%Y-%m-%d ', time.localtime())
        values = dt_cal([temp + s for s in strings])
        ticks = [(i, j) for i, j in zip(values, strings)]
        stringaxis = pg.AxisItem(orientation='bottom')
        stringaxis.setTicks([ticks])

        self.timebar_w1 = pg.PlotWidget(axisItems={'bottom': stringaxis})
        self.timebar_w1.setXRange(min(values), max(values))
        self.timebar_w1.setLimits(xMax=max(values), xMin=min(values))
        self.timebar_p1 = self.timebar_w1.plot(x=self.timebar_t, y=self.timebar_p)
        self.timebar_d1.addWidget(self.timebar_w1)

        self.timebar_w2 = pg.PlotWidget(axisItems={'bottom': stringaxis})
        self.timebar_w2.setXRange(min(values), max(values))
        self.timebar_w2.setLimits(xMax=max(values), xMin=min(values))
        self.timebar_p2 = self.timebar_w2.plot(x=self.timebar_t, y=self.timebar_v, fillLevel=0.0, brush=(50, 50, 200, 100), pen=(50, 50, 200, 100))
        self.timebar_d2.addWidget(self.timebar_w2)
Beispiel #9
0
    def Kline_plotting(self):
        
        #numd=self.data.df.reset_index()
        self.numd=self.data.code_data.reset_index()
        x=self.numd.date.apply(lambda x:datetime.datetime.strftime(x,"%Y-%m-%d"))
        self.xdict=dict(x) #转换成字符串字典
        # LABEL 10个图标
        self.maxRegion=len(self.numd.index)
        t=len(self.numd.index)//5
        #提取坐标点
        axis_date = [(i,list(x)[i]) for i in range(0,len(self.numd.index),t)]
 
        #stringaxis = pg.AxisItem(orientation='bottom')
        stringaxis = pg.AxisItem(orientation='bottom') #设置横轴
        stringaxis.setTicks([axis_date, self.xdict.items()])
        stringaxis.setGrid(255)
        stringaxis.setLabel( text='Dates' )
        #stringaxis.setTickSpacing(100,1)
        self.k_plot = self.win.addPlot(row=1,col=0,title="kline",axisItems={'bottom': stringaxis})
        
        self.y=self.numd.close
        self.k_plot.plot(x=list( self.xdict.keys()), y=self.y.values,pen=(0,255,255))
        
        self.k_plot.showGrid(x=True, y=True)
        self.region = pg.LinearRegionItem()
        self.region.setZValue(self.maxRegion/4*3)
        self.region.setRegion([self.maxRegion/4*3, self.maxRegion])
        self.k_plot.addItem(self.region , ignoreBounds=True)
    def PlotVolumeChart(self, plt, uniqueID):
        p3 = pg.ViewBox()
        p3.setObjectName(uniqueID)
        ax3 = pg.AxisItem('right')
        plt.layout.addItem(ax3, 2,3)
        plt.scene().addItem(p3)
        ax3.linkToView(p3)
        p3.setXLink(plt)
        ax3.setZValue(-100000)
        

        if uniqueID.find('CE') != -1 or uniqueID.find('PE') != -1:
            ax3.setLabel('Volume', color='blue')
        else:
            ax3.setLabel('Volume', color='yellow')

        item2 = None
        if uniqueID.find('CE') != -1:
            item2 = pg.BarGraphItem(x=range(2), height=[0,0], width=0.9, name='Volume', brush='b', pen='b')
        elif uniqueID.find('PE') != -1:
            item2 = pg.BarGraphItem(x=range(2), height=[0,0], width=0.3, name='Volume', brush='r', pen='r')
        else:
            item2 = pg.BarGraphItem(x=range(2), height=[0,0], width=0.5, name='Volume', brush='g', pen='y')

        item2.setOpacity(0.5)
        item2.setObjectName(uniqueID)
        p3.addItem(item2)
        self.plotsDict[p3] = plt
        self.graphs.append(item2)
        plt.vb.sigResized.connect(self.updateViews)
def main(): 
    global p1, p2, p3, QApp, pw
    pg.mkQApp()

    pw = pg.PlotWidget()
    pw.show()
    pw.setWindowTitle('pyqtgraph example: MultiplePlotAxes')
    p1 = pw.plotItem
    p1.setLabels(left='axis 1')
    
    ## create a new ViewBox, link the right axis to its coordinate system
    p2 = pg.ViewBox()
    p1.showAxis('right')
    p1.scene().addItem(p2)
    p1.getAxis('right').linkToView(p2)
    p2.setXLink(p1)
    p1.getAxis('right').setLabel('axis2', color='#0000ff')

    # create third ViewBox. 
    # this time we need to create a new axis as well.
    p3 = pg.ViewBox()
    ax3 = pg.AxisItem('right')
    p1.layout.addItem(ax3, 2, 3)
    p1.scene().addItem(p3)
    ax3.linkToView(p3)
    p3.setXLink(p1)
    ax3.setZValue(-10000)
    ax3.setLabel('axis 3', color='#ff0000')
    
    updateViews()
    p1.vb.sigResized.connect(updateViews)
    
    p1.plot([1,2,4,8,16,32])
    p2.addItem(pg.PlotCurveItem([10,20,40,80,40,20], pen='b'))
    p3.addItem(pg.PlotCurveItem([3200,1600,800,400,200,100], pen='r'))
Beispiel #12
0
 def setXTicks(self, mode=0):
     if mode == 0:
         axis = pyqtlib.TimeAxisItem(True, orientation='bottom')
         axis.attachToPlotItem(
             self.plot.getPlotItem())  # THIS LINE CREATES A WARNING
         self.config['GUI']['timeAxis'] = True
         self.plot.getPlotItem().setLabel(
             "bottom", translate('RTOC', "Elapsed time [s]"), "")
     elif mode == 1:
         axis = pg.AxisItem(orientation='bottom')
         axis.setParentItem(self.plot.getPlotItem())
         viewBox = self.plot.getPlotItem().getViewBox()
         axis.linkToView(viewBox)
         axis._oldAxis = self.plot.getPlotItem().axes[
             axis.orientation]['item']
         axis._oldAxis.hide()
         self.plot.getPlotItem().axes[axis.orientation]['item'] = axis
         pos = self.plot.getPlotItem().axes[axis.orientation]['pos']
         self.plot.getPlotItem().layout.addItem(axis, *pos)
         axis.setZValue(-1000)
         self.plot.getPlotItem().setLabel("bottom", "", "")
     elif mode == 2:
         axis = pyqtlib.TimeAxisItem(False, orientation='bottom')
         axis.attachToPlotItem(
             self.plot.getPlotItem())  # THIS LINE CREATES A WARNING
         self.config['GUI']['timeAxis'] = True
         self.plot.getPlotItem().setLabel("bottom",
                                          translate('RTOC', "Date/Time"),
                                          "")
Beispiel #13
0
    def __init__(self, tvar, last_plot=False):
        
        self.tvar=tvar
        self.last_plot = last_plot
        
        #Sets up the layout of the Tplot Object
        pg.GraphicsLayout.__init__(self)
        self.layout.setHorizontalSpacing(50)
        self.layout.setContentsMargins(0,0,0,0)
        #Set up the x axis
        self.xaxis = DateAxis(orientation='bottom')
        self.xaxis.setHeight(35)
        self.xaxis.enableAutoSIPrefix(enable=False)
        #Set up the y axis
        self.yaxis = pg.AxisItem("left")
        self.yaxis.setWidth(100)
        
        self.plotwindow = self.addPlot(row=0, col=0, axisItems={'bottom': self.xaxis, 'left': self.yaxis})
        
        #Set up the view box needed for the legends
        self.legendvb = pg.ViewBox(enableMouse=False)
        self.legendvb.setMaximumWidth(100)
        self.legendvb.setXRange(0,1, padding=0)
        self.legendvb.setYRange(0,1, padding=0)
        self.addItem(self.legendvb,0,1)       
        
        
        self.curves = []
        self.colors = self._setcolors()
        self.colormap = self._setcolormap()

        if last_plot:
            self.plotwindow.showAxis('bottom')
        else:
            self.plotwindow.hideAxis('bottom')
Beispiel #14
0
    def __init__(self, parent=None, inputFilename="DefaultFilename", data_files='models_v06'):
        super(MainApp, self).__init__(parent)
        self.setupUi(self)

        self.mainDirectory = os.path.dirname(os.path.abspath(__file__))
        self.data_files = data_files
        self.templates()
        self.plotted = False
        self.plotZ = 0
        self.hostFraction = 0
        self.inputFluxes = np.zeros((2, int(self.nw)))
        self.inputImageUnRedshifted = np.zeros(int(self.nw))
        self.templatePlotFlux = np.zeros(int(self.nw))
        self.templateSubIndex = 0
        self.snName = 'Ia-norm'
        self.snAge = '-20 to -18'
        self.hostName = 'No Host'
        self.lineEditKnownZ.setText('')
        self.infLine = pg.InfiniteLine(self.plotZ, pen={'width': 3, 'color': (135, 206, 250)}, movable=True,
                                       bounds=[-1, 1], hoverPen={'color': (255, 0, 0), 'width': 3}, label='z',
                                       labelOpts={'color': (135, 206, 250), 'position': 0.2})
        self.infLine.sigPositionChanged.connect(self.cross_corr_redshift_changed)

        self.pushButtonLeftTemplate.clicked.connect(self.select_sub_template_left)
        self.pushButtonRightTemplate.clicked.connect(self.select_sub_template_right)
        self.btnBrowse.clicked.connect(self.select_input_file)
        self.listWidget.itemClicked.connect(self.list_item_clicked)
        self.btnRefit.clicked.connect(self.fit_spectra)
        self.inputFilename = inputFilename
        self.inputFilenameSetText = inputFilename
        self.progressBar.setValue(100)
        self.add_combo_box_entries()
        self.labelRlapScore.setText('')

        self.select_tensorflow_model()
        self.checkBoxKnownZ.stateChanged.connect(self.select_tensorflow_model)
        self.checkBoxClassifyHost.stateChanged.connect(self.select_tensorflow_model)

        self.lineEditInputFilename.textChanged.connect(self.input_filename_changed)

        self.horizontalSliderSmooth.valueChanged.connect(self.smooth_slider_changed)
        self.lineEditSmooth.textChanged.connect(self.smooth_text_changed)

        self.horizontalSliderRedshift.valueChanged.connect(self.redshift_slider_changed)
        self.lineEditRedshift.textChanged.connect(self.redshift_text_changed)

        self.horizontalSliderHostFraction.valueChanged.connect(self.host_fraction_slider_changed)
        self.lineEditHostFraction.editingFinished.connect(self.host_fraction_text_changed)

        self.comboBoxSNType.currentIndexChanged.connect(self.combo_box_changed)
        self.comboBoxAge.currentIndexChanged.connect(self.combo_box_changed)
        self.comboBoxHost.currentIndexChanged.connect(self.combo_box_changed)

        self.btnQuit.clicked.connect(self.close)

        self.graphicsView.plotItem.layout.removeItem(self.graphicsView.plotItem.getAxis('top'))
        self.cAxis = pg.AxisItem(orientation='top', parent=self.graphicsView.plotItem)
        self.cAxis.linkToView(self.graphicsView.plotItem.vb)
        self.graphicsView.plotItem.axes['top']['item'] = self.cAxis
        self.graphicsView.plotItem.layout.addItem(self.cAxis, 1, 1)
Beispiel #15
0
    def printRealBarChar(self, plot, xDict):
        x1 = list(xDict.keys())
        y1 = list(xDict.values())
        stringAxis = qtPlot.AxisItem(orientation='bottom')

        bg1 = qtPlot.BarGraphItem(x=x1, height=y1, width=0.6)
        plot.addItem(bg1)
    def macd_plotting2(self):
        self.macd_type = 1
        t = len(self.numd.index) // 10

        axis_date = [(i, list(self.xdict.values())[i])
                     for i in range(0, len(self.numd.index), t)]
        stringaxis = pg.AxisItem(orientation='bottom')  #设置横轴
        stringaxis.setTicks([axis_date, self.xdict.items()])
        #stringaxis.setGrid(255)
        stringaxis.setLabel(text='Dates')
        self.macd_plot2 = self.win.addPlot(
            row=2, col=1, title="MACD2", axisItems={'bottom': stringaxis})

        macd, signal, hist = self.data.myMACD2()
        self.macd_plot2.plot(
            x=self.y.index,
            y=macd.values,
            pen='r',
            fillLevel=0,
            fillBrush=(255, 0, 0, 50))
        self.macd_plot2.plot(
            x=self.y.index,
            y=signal.values,
            pen='b',
            fillLevel=0,
            fillBrush=(0, 125, 255, 126))
        self.macd_plot2.plot(x=self.y.index, y=self.y.index * 0, pen='w')
        self.macd_plot2.setXLink(self.update_plot)
        self.macd_plot2.showGrid(x=True, y=True)
 def _addlegend(self):
     zaxis=pg.AxisItem('right')
     
     if 'axis_label' in pytplot.data_quants[self.tvar_name].zaxis_opt:
         zaxis.setLabel(pytplot.data_quants[self.tvar_name].yaxis_opt['axis_label'])
     else:
         zaxis.setLabel(' ')
     
     if self.show_xaxis:
         emptyAxis=BlankAxis('bottom')
         emptyAxis.setHeight(35)
         p2 = self.addPlot(row=0, col=1, axisItems={'right':zaxis, 'bottom':emptyAxis}, enableMenu=False, viewBox=self.legendvb)
     else:
         p2 = self.addPlot(row=0, col=1, axisItems={'right':zaxis}, enableMenu=False, viewBox=self.legendvb)
         p2.hideAxis('bottom')
         
     p2.buttonsHidden=True
     p2.setMaximumWidth(100)
     p2.showAxis('right')
     p2.hideAxis('left')
     colorbar = pg.ImageItem()
     colorbar.setImage(np.array([np.linspace(1,2,200)]).T)
     
     p2.addItem(colorbar)
     p2.setLogMode(y=(self.zscale=='log'))
     p2.setXRange(0,1, padding=0)
     if self.zscale=='log':
         colorbar.setRect(QtCore.QRectF(0,np.log10(self.zmin),1,np.log10(self.zmax)-np.log10(self.zmin)))
         #I have literally no idea why this is true, but I need to set the range twice
         p2.setYRange(np.log10(self.zmin),np.log10(self.zmax), padding=0)
         p2.setYRange(np.log10(self.zmin),np.log10(self.zmax), padding=0)
     else:
         colorbar.setRect(QtCore.QRectF(0,self.zmin,1,self.zmax-self.zmin))
         p2.setYRange(self.zmin,self.zmax, padding=0)
     colorbar.setLookupTable(self.colormap)
Beispiel #18
0
    def __init__(self, title: str, x_tick_labels: List[str],
                 position: Optional[ScatterPlotPosition]):
        """
        Initialize the scatter plot.

        :param title: Title.
        :param x_tick_labels: Labels for the x-axis ticks.
        :param position: Position, or None to place the plot automatically on the screen.
        """

        if position is None:
            position = ScatterPlot.next_position
            if position == ScatterPlotPosition.TOP_LEFT:
                ScatterPlot.next_position = ScatterPlotPosition.TOP_RIGHT
            elif position == ScatterPlotPosition.TOP_RIGHT:
                ScatterPlot.next_position = ScatterPlotPosition.BOTTOM_RIGHT
            elif position == ScatterPlotPosition.BOTTOM_RIGHT:
                ScatterPlot.next_position = ScatterPlotPosition.BOTTOM_LEFT
            else:
                ScatterPlot.next_position = ScatterPlotPosition.TOP_LEFT

        self.title = title
        self.x_tick_labels = x_tick_labels
        self.position = position

        self.plot_layout = pg.GraphicsLayoutWidget(show=True, title=title)
        plot_x_axis = pg.AxisItem(orientation='bottom')
        plot_x_axis.setTicks([list(enumerate(self.x_tick_labels))])
        self.plot_widget = self.plot_layout.addPlot(
            axisItems={'bottom': plot_x_axis})
        self.plot_item = None
        self.plot_x_vals = list(range(len(x_tick_labels)))
        self.plot_max_abs_y = None

        self.set_position(self.position)
Beispiel #19
0
 def add_new_plot(zvalue):
     plot = pg.ViewBox(enableMouse=False, enableMenu=False)
     self.ploti.scene().addItem(plot)
     pg.AxisItem("right").linkToView(plot)
     plot.setXLink(self.ploti)
     plot.setZValue(zvalue)
     return plot
Beispiel #20
0
    def __init__(self, mainWidget, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.main = mainWidget
        self.npoints = 200

        self.setAntialiasing(True)

        # First plot for the number of molecules
        self.plot1 = self.plotItem
        self.plot1.setLabels(bottom=('Tiempo', 's'),
                             left=('Number of single molecules'))
        self.plot1.showGrid(x=True, y=True)
        self.curve1 = self.plot1.plot(pen='y')
        self.plot1.vb.setLimits(yMin=-0.5)

        # Second plot for the number of overlaps
        self.plot2 = pg.ViewBox()
        self.ax2 = pg.AxisItem('right')
        self.plot1.layout.addItem(self.ax2, 2, 3)
        self.plot1.setLimits(yMin=-0.5)
        self.plot1.scene().addItem(self.plot2)
        self.ax2.linkToView(self.plot2)
        self.plot2.setXLink(self.plot1)
        self.ax2.setLabel('Number of overlaps')
        self.curve2 = pg.PlotCurveItem(pen='r')
        self.plot2.addItem(self.curve2)
        self.plot2.setLimits(yMin=-0.5)

        # Handle view resizing
        self.updateViews()
        self.plot1.vb.sigResized.connect(self.updateViews)

        self.fwhm = tools.get_fwhm(670, 1.42) / 120
        self.kernel = tools.kernel(self.fwhm)
Beispiel #21
0
    def _refresh_multi_axis(self):
        """If linked axis' are used, setup and link them"""
        d = self.declaration

        #: Create a separate viewbox
        self.viewbox = pg.ViewBox()

        #: If this is the first nested plot, use the parent right axis
        _plots = [
            c for c in self.parent().children()
            if isinstance(c, AbstractQtPlotItem)
        ]
        i = _plots.index(self)
        if i == 0:
            self.axis = self.widget.getAxis("right")
            self.widget.showAxis("right")
        else:
            self.axis = pg.AxisItem("right")
            self.axis.setZValue(-10000)

            #: Add new axis to scene
            self.widget.layout.addItem(self.axis, 2, i + 2)

        #: Link x axis to the parent axis
        self.viewbox.setXLink(self.widget.vb)

        #: Link y axis to the view
        self.axis.linkToView(self.viewbox)

        #: Set axis label
        self.axis.setLabel(d.label_right)

        #: Add Viewbox to parent scene
        self.parent().parent_widget().scene().addItem(self.viewbox)
Beispiel #22
0
    def draw_volums(self):
        self.plt2.plotItem.clear()
        y = self.Volumns
        a = len(y)
        x = []
        t = 0
        for i in range(0, a):
            i += 0
            x.append(i)
            t += 1

    # 创建X轴及刻度
        self.xdict = {
            0:
            str(self.df.index[0]).replace('-', '/'),
            int((t + 1) / 2) - 1:
            str(self.df.index[int((t + 1) / 2)]).replace('-', '/'),
            t - 2:
            str(self.df.index[-1]).replace('-', '/')
        }
        self.stringaxis = pg.AxisItem(orientation='bottom')
        self.stringaxis.setTicks([self.xdict.items()])
        self.plt2.plot(y, pen='b')
        self.plt2.getAxis('bottom').setTicks([self.xdict.items()])
        bg1 = pg.BarGraphItem(x=x, height=y, width=1, pen='b')
        self.plt2.addItem(bg1)
        name = str(self.code + self.name)
        self.plt2.setTitle(name, color='w')
Beispiel #23
0
    def SI_Plot(self, currentItem, selectedItems):
        self.CI_Plot(currentItem)
        self.chartPlotItems[0].vb.sigResized.connect(self.updateViews)
        j = 2
        # print(j)
        for i in range(0, len(selectedItems)):

            if selectedItems[i] != currentItem:
                # print('3')
                temp_vb = pyqtgraph.ViewBox()

                ax_temp = pyqtgraph.AxisItem('right')

                # self.chartPlotItems[0].layout.clear()

                self.chartPlotItems[0].layout.addItem(ax_temp, 2, j)
                self.chartPlotItems[0].scene().addItem(temp_vb)
                ax_temp.linkToView(temp_vb)
                temp_vb.setXLink(self.chartPlotItems[0])
                ax_temp.setLabel('axial ' + str(j), color=self.colorDex[i])
                # print('4')
                temp_2_plot = self.dataSummary[int(selectedItems[i].text(0))]
                # print(temp_2_plot[:100])
                temp_plotcurve = pyqtgraph.PlotCurveItem(
                    [float(x) for x in temp_2_plot], pen=self.colorDex[i])
                temp_vb.addItem(temp_plotcurve)

                self.chartVBs.append(temp_vb)
                self.chartAxials.append(ax_temp)
                self.chartCurve.append(temp_plotcurve)
                # print('5')

                j = j + 1
Beispiel #24
0
 def getView(self, id):
     from UserView import widgetView
     self.sql_cursor = self.sql_conn.cursor()
     self.sql_cursor.execute(
         'select io_send,io_receive,action_time from loginfo_table where id=%s',
         (id, ))
     back_msg = self.sql_cursor.fetchall()
     if back_msg != []:
         info = {}
         for i in back_msg:
             datestr = i[2].split(' ')[0]
             if datestr not in info.keys():
                 info[datestr] = [i[0], i[1]]
             else:
                 info[datestr][0], info[datestr][1] = round(
                     info[datestr][0] + i[0],
                     4), round(info[datestr][1] + i[1], 4)
         plot_tuple = sorted(info.items(), key=lambda f: f[0])
         key_label = [k[0] for k in plot_tuple]
         send_list = [k[1][0] for k in plot_tuple]
         re_list = [k[1][1] for k in plot_tuple]
         xdict = dict(enumerate(key_label))
         stringaxis = pg.AxisItem(orientation='bottom')
         stringaxis.setTicks([xdict.items()])
         self.newWidget = widgetView(id)
         self.newWidget.plotall(stringaxis, xdict, send_list, re_list)
         self.newWidget.show()
     else:
         QMessageBox.warning(self, "Warning", "No Data!", QMessageBox.Yes)
Beispiel #25
0
    def __init__(self, tvar_name):
        self.tvar_name = tvar_name
        
        # Sets up the layout of the Tplot Object
        pg.GraphicsLayout.__init__(self)
        self.layout.setHorizontalSpacing(50)
        self.layout.setContentsMargins(0, 0, 0, 0)

        self.labelStyle = {'font-size': str(pytplot.data_quants[self.tvar_name].extras['char_size'])+'pt'}
        
        vb = CustomVB(enableMouse=False)
        yaxis = pg.AxisItem("left")
        yaxis.setLabel(pytplot.data_quants[self.tvar_name].yaxis_opt['axis_label'], **self.labelStyle)
        yaxis.setWidth(100)
        yaxis.label.rotate(90)
        yaxis.label.translate(0, -40)
        xaxis = NonLinearAxis(orientation='bottom', data=pytplot.data_quants[self.tvar_name])
        self.plotwindow = self.addPlot(row=0, col=0, axisItems={'bottom': xaxis, 'left': yaxis}, viewBox=vb, colspan=1)
        self.plotwindow.buttonsHidden = True
        self.plotwindow.setMaximumHeight(20)
        
        # Set up the view box needed for the legends
        self.legendvb = pg.ViewBox(enableMouse=False)
        self.legendvb.setMaximumWidth(100)
        self.addItem(self.legendvb, 0, 1)
Beispiel #26
0
    def new_y_axis(self):
        self._num_y_axes += 1

        pi = self.getPlotItem()
        if self._num_y_axes == 1:
            return pi.getAxis("left"), pi.getViewBox()

        vb = pyqtgraph.ViewBox()

        if self._num_y_axes == 2:
            # With more than one axis, we need to start resizing the linked views.
            pi.getViewBox().sigResized.connect(
                self._update_additional_view_boxes)

            pi.showAxis("right")
            axis = pi.getAxis("right")
        else:
            axis = pyqtgraph.AxisItem("right")
            # FIXME: Z value setting is cargo-culted in from the pyqtgraph example –
            # what should the correct value be?
            axis.setZValue(-10000)
            self._additional_right_axes.append(axis)
            pi.layout.addItem(axis, 2, self._num_y_axes)

        pi.scene().addItem(vb)
        axis.linkToView(vb)
        axis.setGrid(False)
        vb.setXLink(pi)
        self._additional_view_boxes.append(vb)
        self._update_additional_view_boxes()
        return axis, vb
Beispiel #27
0
 def attachAxis(self, axisDescriptor):
     if self.nAxis == 0:
         viewBox = self.plotItem
         axis = viewBox.getAxis('left')
     else:
         viewBox = pg.ViewBox()
         axis = pg.AxisItem('right')
         self.plotItem.scene().addItem(viewBox)
         self.plotItem.layout.addItem(axis, 2, self.nAxis + 2)
         axis.linkToView(viewBox)
         viewBox.setXLink(self.plotItem)
         self.updateViews(viewBox)
         self.plotItem.vb.sigResized.connect(
             lambda: self.updateViews(viewBox))
     self.nAxis += 1
     #        self.viewBoxes.append(viewBox)
     if type(axisDescriptor) is not dict:
         axisDescriptor = {'curves': axisDescriptor}
     elif 'source' in axisDescriptor:
         self.attachCurve(axisDescriptor, viewBox)
         return
     if type(axisDescriptor['curves']) is not list:
         axisDescriptor['curves'] = [axisDescriptor['curves']]
     for curve in axisDescriptor['curves']:
         self.attachCurve(curve, viewBox)
Beispiel #28
0
    def __init__(self, device_index, pyaudio_object):

        # pyqtgraph stuff
        pg.setConfigOptions(antialias=True)
        self.traces = dict()
        self.app = QtGui.QApplication(sys.argv)
        self.win = pg.GraphicsWindow(title='Audio Visualizer')
        self.win.setWindowTitle('Audio Visualizer')
        self.win.setGeometry(5, 115, 1910, 1070)

        wf_xlabels = [(0, '0'), (2048, '2048'), (4096, '4096')]
        wf_xaxis = pg.AxisItem(orientation='bottom')
        wf_xaxis.setTicks([wf_xlabels])

        wf_ylabels = [(-1, '-1'), (0, '0'), (1, '1')]
        wf_yaxis = pg.AxisItem(orientation='left')
        wf_yaxis.setTicks([wf_ylabels])

        self.waveform = self.win.addPlot(
            title='WAVEFORM',
            row=1,
            col=1,
            axisItems={
                'bottom': wf_xaxis,
                'left': wf_yaxis
            },
        )

        # constants
        self.RATE = 44100
        self.CHUNK = 2048
        self.CHANNELS = 2
        self.DATA_TYPE = np.int16
        self.useloopback = True
        self.deviceIndex = device_index

        # members
        self.p = pyaudio_object
        self.stream = self.p.open(format=pyaudio.paInt16,
                                  channels=self.CHANNELS,
                                  rate=self.RATE,
                                  input=True,
                                  frames_per_buffer=self.CHUNK,
                                  input_device_index=self.deviceIndex,
                                  as_loopback=self.useloopback)

        self.x = np.arange(0, 2 * self.CHUNK, 2)
    def __init__(self, parent=None):
        super(LockinThermometerWidget, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle('Lockin Thermometer')
        self.timer = None
        self.Rthermometer = float('nan')


        '''
        Not sure if DateAxisItem is available anymore
        '''
        axis = pg.AxisItem(orientation='bottom')
        self.plot = pg.PlotWidget(axisItems={'bottom': axis})
        self.plot.setBackground('w')
        self.plot.plotItem.showGrid(x=True, y=True)
        self.plot.addLegend()
        self.verticalLayout.addWidget(self.plot)
        self.curve = pg.PlotCurveItem(name='X', symbol='o', pen='b')
        self.plot.addItem(self.curve)
        self.clearPb.clicked.connect(self.clearData)
        self.clearData()
        self.plotYAxisCombo.currentIndexChanged.connect(self.updatePlot)
        
        self.sr830 = None
        self.runPb.clicked.connect(self.run)
        self.parameterItems = [self.attenuatorGainSb, self.sourceImpedanceSb, self.driveResistanceSb, self.leadResistanceSb, self.preampGainSb, self.sensorVoltageSb]
        self.savePb.clicked.connect(self.saveParameterSet)
        self.loadPb.clicked.connect(self.loadParameterSet)
        self.deletePb.clicked.connect(self.deleteParameterSet)
        self.attenuatorAttenuationSb.valueChanged.connect(self.updateAttenuatorGain)
        self.attenuatorGainSb.valueChanged.connect(self.updateAttenuatorAttenuation)
        self.sensorVoltageIndicator.setUnit('V')
        self.sensorCurrentIndicator.setUnit('A')
        self.sensorPowerIndicator.setUnit('W')

        sr830 = SR830(None)
        sr830.sensitivity.populateEnumComboBox(self.minSensitivityCombo)
        
        self.loadParameterSets()
        self.restoreSettings()
        self.hkSub = HousekeepingSubscriber(parent = self)
        self.hkSub.adrResistanceReceived.connect(self.collectAdrResistance)
        self.hkSub.start()
        self.adrResistanceIndicator.setUnit(u'Ω')
        self.adrResistanceIndicator.setPrecision(5)
        self.publisher = None
        
        combo = self.calibrationCombo
        combo.addItem('RuOx 600')
        combo.addItem('RuOx 2005')
        combo.addItem('RuOx Bus (Shuo)')
        combo.addItem('RuOx Chip (InsideBox)')
        combo.setItemData(0, 'Nominal sensor calibration for RuOx 600 series', Qt.ToolTipRole)
        combo.setItemData(1, 'Calibration for RuOx sensor #2005 series', Qt.ToolTipRole)
        combo.setItemData(2, 'Cross-calibration against RuOx #2005 by Shuo (not so good above ~300mK)', Qt.ToolTipRole)
        combo.setItemData(3, 'Cross-calibration against RuOx #2005 by Yu', Qt.ToolTipRole)
        
        self.selectCalibration()
        combo.currentIndexChanged.connect(self.selectCalibration)
Beispiel #30
0
    def draw_graphs(self):
        self.graphicsView.plotItem.clear()
        self._user = self._client.get_user(self._user.id)
        self._currency = self._client.get_user_currency(
            self._user.id, self._currency.id)
        pg.setConfigOptions(antialias=True)
        history_items: List[
            CurrencyHistory] = self._client.get_currency_history(
                self._currency.id)
        selling_prices = list(
            map(lambda item: float(item.selling_price), history_items))
        purchasing_prices = list(
            map(lambda item: float(item.purchasing_price), history_items))
        time = {}
        for i in range(len(history_items)):
            if i == 0 or i == len(history_items) - 1:
                time[i] = datetime.strftime(history_items[i].time,
                                            '%Y-%m-%d %H:%M:%S')
            else:
                time[i] = ''
        self.set_text_info(
            selling_prices[-1],
            purchasing_prices[-1],
            str(self._user.money),
            str(self._currency.amount),
            self._currency.name,
        )
        self.graphicsView.setBackground('w')

        self.graphicsView.addLegend()

        time_axis = pg.AxisItem(orientation='bottom')
        time_axis.setTicks([time.items()])
        self.graphicsView.setAxisItems(axisItems={'bottom': time_axis})

        self.graphicsView.setLabel('left', 'Цена')
        self.graphicsView.setLabel('bottom', 'Время')

        self.graphicsView.showGrid(x=True, y=True)

        self.plot(
            list(time.keys()),
            purchasing_prices,
            'Цена покупки',
            (0, 220, 0),
            1.5,
            'o',
            5,
        )

        self.plot(
            list(time.keys()),
            selling_prices,
            'Цена продажи',
            (255, 0, 0),
            1.5,
            'o',
            5,
        )