当前位置: 首页>>代码示例>>Python>>正文


Python NavigationToolbar2QT.close方法代码示例

本文整理汇总了Python中matplotlib.backends.backend_qt4agg.NavigationToolbar2QT.close方法的典型用法代码示例。如果您正苦于以下问题:Python NavigationToolbar2QT.close方法的具体用法?Python NavigationToolbar2QT.close怎么用?Python NavigationToolbar2QT.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.backends.backend_qt4agg.NavigationToolbar2QT的用法示例。


在下文中一共展示了NavigationToolbar2QT.close方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Mpl

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QT import close [as 别名]
class Mpl(QtGui.QWidget, Ui_Form):
    def __init__(self, fig_dict, name_list):
        super(Mpl, self).__init__()
        self.setupUi(self)
        self.fig_dict = fig_dict
        self.name_list = name_list
        self.index = 0

        self.btnBack.clicked.connect(self.back)
        self.btnForward.clicked.connect(self.forward)

        self.comboBoxSelect.addItems(self.name_list)
        self.comboBoxSelect.setCurrentIndex(self.index)
        self.comboBoxSelect.activated.connect(self.select)
        
        if self.fig_dict and self.name_list:
            fig = self.fig_dict[self.name_list[self.index]]
        else:
            fig = Figure()
        self.addmpl(fig)

    def changefig(self,):
        self.comboBoxSelect.setCurrentIndex(self.index)
        fig = self.fig_dict[self.name_list[self.index]]
        self.rmmpl()
        self.addmpl(fig)

    def addmpl(self, fig):
        self.canvas = FigureCanvas(fig)
        # self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)
        self.ltMPL.addWidget(self.canvas)
        self.canvas.draw()
        self.toolbar = NavigationToolbar(self.canvas, 
                self.wgtToolbox, coordinates=True)
        self.ltToolbox.addWidget(self.toolbar)

    def rmmpl(self,):
        self.ltMPL.removeWidget(self.canvas)
        self.canvas.close()
        self.ltToolbox.removeWidget(self.toolbar)
        self.toolbar.close()

    def back(self):
        self.index = self.index-1 if self.index!=0 else len(self.name_list)-1
        self.changefig()

    def forward(self):
        self.index = self.index+1 if self.index!=len(self.name_list)-1 else 0
        self.changefig()

    def select(self):
        self.index = self.comboBoxSelect.currentIndex()
        self.changefig()
开发者ID:sig-app,项目名称:PlotViewer,代码行数:55,代码来源:MplCtrl.py

示例2: Main

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QT import close [as 别名]
class Main(QMainWindow, Ui_MainWindow):
    def __init__(self, ):
        super(Main, self).__init__()
        self.setupUi(self)
        self.fig_dict = {}

        self.mplfigs.itemClicked.connect(self.changefig)

        fig = Figure()
        self.addmpl(fig)

    def changefig(self, item):
        text = item.text()
        self.rmmpl()
        self.addmpl(self.fig_dict[text])

    def addfig(self, name, fig):
        self.fig_dict[name] = fig
        self.mplfigs.addItem(name)

    def addmpl(self, fig):
        self.canvas = FigureCanvas(fig)
        self.mplvl.addWidget(self.canvas)
        self.canvas.draw()
        self.toolbar = NavigationToolbar(self.canvas, 
                self.mplwindow, coordinates=True)
        self.mplvl.addWidget(self.toolbar)
# This is the alternate toolbar placement. Susbstitute the three lines above
# for these lines to see the different look.
#        self.toolbar = NavigationToolbar(self.canvas,
#                self, coordinates=True)
#        self.addToolBar(self.toolbar)

    def rmmpl(self,):
        self.mplvl.removeWidget(self.canvas)
        self.canvas.close()
        self.mplvl.removeWidget(self.toolbar)
        self.toolbar.close()
开发者ID:3WiseMen,项目名称:python,代码行数:40,代码来源:custommpl.py

示例3: Main

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QT import close [as 别名]
class Main(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, ):
        super(Main, self).__init__()
        self.setupUi(self)
        self.StartButton.clicked.connect(self.loadFile)
        self.NextButton.clicked.connect(self.nextRecord)
        self.DeleteButton.clicked.connect(self.deleteRecord)
        self.GenerateButton.clicked.connect(self.generateRecord)
        self.QuitButton.clicked.connect(self.quit)
        self.horiz = GetSystemMetrics(0)
        self.verti = GetSystemMetrics(1)
        self.subjectNo = 0;
        self.dayNo = 0;
        self.blockNo = 0;
        self.center_no = 0;
        self.tr_no = 0;
        self.old_x = 0
        self.old_y = 0
        self.old_t = 0
        self.start=0;
        self.vel_thresh = 500/4.25; #in pix/s
        self.deleteThisRecord = 0;
        self.generateAll = 0;
        self.fileReadDone = 0;
        self.AllStrings = [];  #raw file.
        self.AllGoodStrings = []; #filtered file
        self.RandomStrings = [];
        self.SequenceStrings = [];
        self.RandomGoodStrings = [];
        self.SequenceGoodStrings = [];
        topics="tr_no Reaction_Time Movement_Time Response_Time Max_Vel Max_Acc End_Point_Dev Real_Distance Actual_Distance_Traversed Distance_Percent\n";
        self.AllStrings.append(topics);
        self.AllGoodStrings.append(topics);
        self.RandomStrings.append(topics);
        self.SequenceStrings.append(topics);
        self.RandomGoodStrings.append(topics);
        self.SequenceGoodStrings.append(topics);
        self.cnx = mysql.connector.connect(user='root',password='neuro',database='mohand');
        self.cursor = self.cnx.cursor();
        self.smoothLevel = 20;

    def addplot(self, fig):
        #plt.savefig('common_labels_text.png', dpi=300)
        self.canvas = FigureCanvas(fig)
        self.mplvl.addWidget(self.canvas)
        self.canvas.draw()
        self.toolbar = NavigationToolbar(self.canvas, self, coordinates=True)
        self.addToolBar(self.toolbar)

    def rmplot(self):
        self.mplvl.removeWidget(self.canvas)
        self.canvas.close()
        self.mplvl.removeWidget(self.toolbar)
        self.toolbar.close()

    def loadFile(self):
        print "load file"
        self.X=[];
        self.Y=[];
        self.D=[];
        self.V=[];
        self.A=[];
        self.T=[];
        self.generateAll = 0;
        self.fileReadDone = 0;
        subNo = self.SubjectText.text()
        d = self.DayCombo.currentIndex()
        self.subjectNo = int(subNo);
        self.dayNo = d+1;
        self.blockNo = self.BlockCombo.currentIndex()+1 
        block = str(self.blockNo);
        day = dayTitle(self.dayNo)
        if self.dayNo<=5:
            s = "C:\\Users\\neuro\\Documents\\Arna\\Tracker\\Data\\Subject "+subNo+"\\Subject" + subNo + day + "Block" + block + "_Data.txt";
        else:
            s = "C:\\Users\\neuro\\Documents\\Arna\\Tracker\\Data\\Subject "+subNo+"\\Subject" + subNo + day + "Data.txt";
        center_file_s = "C:\\Users\\neuro\\Documents\\Visual Studio 2015\\Projects\\MohandTracker\\Mohands(4,6,5).txt";
        print s
        self.file = open(s, 'r');
        self.center_file = open(center_file_s, 'r');
        self.center_array = [[int(x) for x in line.split()] for line in self.center_file];
        #print self.center_array
        self.center_array_size = len(self.center_array[0]);
        self.tr_no = 0;
        self.start = 0;
        self.smoothLevel = int(self.text_smooth.text());
        self.getFig();
        
        
        
    def getFig(self):
        plt.close("all");
        s1 = str(self.tr_no);
        s2 = str(self.tr_no+1);
        self.FromLabel.setText(s1);
        self.ToLabel.setText(s2);
        reac_time = 0;
        react_time_set = 0;
        response_time = 0;
        
#.........这里部分代码省略.........
开发者ID:arnaghosh,项目名称:MITACS,代码行数:103,代码来源:main_analyser.py

示例4: MainWindow

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QT import close [as 别名]
class MainWindow(QtGui.QMainWindow, OnClick, OnMotion):
    def __init__(self):
        super(MainWindow, self).__init__()
        uic.loadUi("PeakInspector_layout.ui", self)
        self.setWindowTitle("PeakInspector (beta) (c) A.Salykin - Masaryk University - CC-BY-SA 4.0")

        # main variable:
        self.multiple_data_sets = pd.DataFrame()  # Initialise the final dataframe to export to Excel

        self.coordinates = []
        self.area = []
        self.amplitudes = []
        self.amplitude_line_coordinates = []
        self.left_peak_border = []
        self.right_peak_border = []
        self.pickable_artists_pts_AX2 = []
        self.pickable_artists_pts_AX3 = []
        self.pickable_artists_lns_AX3 = []
        self.pickable_artists_fill_AX3 = []
        self.pickable_artists_plb_AX3 = []
        self.pickable_artists_prb_AX3 = []
        self.pickable_artists_lnsP_AX3 = []

        self.left_border = []
        self.right_border = []

        # Connect buttons to class methods:
        self.BtnLoadFile.clicked.connect(self.load_file)
        self.BtnReplot.clicked.connect(self.replot_graph)
        self.chbxDotPickEnable.stateChanged.connect(self.dot_pick_enable)
        self.BtnSaveCurrent.clicked.connect(self.coordinates_analysis)
        self.BtnSaveFullDataset.clicked.connect(self.save_data)
        self.BoxMplPlotStyle.currentIndexChanged.connect(self.mpl_style_change)

        style.use(self.BoxMplPlotStyle.currentText())

        self.BtnLoadFile.setStyleSheet("background-color: #7CF2BD")
        self.BtnReplot.setStyleSheet("background-color: #FAF6F2")
        self.BtnSaveCurrent.setStyleSheet("background-color: #FAF6F2")
        self.BtnSaveFullDataset.setStyleSheet("background-color: #FAF6F2")

        # Initialise figure instance
        self.fig = plt.figure()
        self.show()

    def addmpl(self, ):
        self.canvas = FigureCanvas(self.fig)
        self.toolbar = NavigationToolbar(self.canvas, self.CanvasWidget, coordinates=True)
        self.CanvasLayout.addWidget(self.toolbar)
        self.CanvasLayout.addWidget(self.canvas)
        if self.chbxDotPickEnable.isChecked():
            self.cid_click = self.canvas.mpl_connect('button_press_event', self.on_click)
            self.cid_motion = self.canvas.mpl_connect('motion_notify_event', self.on_motion)
        self.canvas.draw()

    def rmmpl(self, ):  #
        self.canvas.mpl_disconnect(self.cid_click)
        self.canvas.mpl_disconnect(self.cid_motion)
        self.CanvasLayout.removeWidget(self.canvas)
        self.canvas.close()
        self.CanvasLayout.removeWidget(self.toolbar)
        self.toolbar.close()

    def dot_pick_enable(self, ):  # if checked, user can choose peaks
        try:  # if figure and canvas is initiated
            if self.chbxDotPickEnable.isChecked():
                self.cid_click = self.canvas.mpl_connect('button_press_event', self.on_click)
                self.cid_motion = self.canvas.mpl_connect('motion_notify_event', self.on_motion)
            else:
                self.canvas.mpl_disconnect(self.cid_click)
                self.canvas.mpl_disconnect(self.cid_motion)
        except:
            message = MessageBox()
            message.about(self, 'Warning!', "File was not loaded! \n Please be sure that your file has \
                \n 1) 1 or 2 columns; \n 2) check headers, footers and delimeter \n and try again.")

    def load_file(self, ):
        self.BtnLoadFile.setStyleSheet("background-color: #FAF6F2")
        # Check if we already have some file loaded - then remove canvas
        if hasattr(self, 'cid_click'):
            self.rmmpl()

        # Make sure that np data arrays and lists from previous dataset are empty
        self.x = np.empty([])
        self.y = np.empty([])
        self.clear_data()

        name = QtGui.QFileDialog.getOpenFileName(self, 'Open File')
        if not name:
            return self.import_error()

        # get more readable file name for graph title
        try:
            slash_index = self.find_character(name, '/')
            dot_index = self.find_character(name, '.')
            self.graph_name = name[slash_index[-1] + 1:dot_index[-1]]
        except:
            self.graph_name = name[-10:]

        skip_header_rows = self.BoxSkipHeader.value()
#.........这里部分代码省略.........
开发者ID:ASalykin,项目名称:PeakInspector,代码行数:103,代码来源:MainWindow.py

示例5: dApp

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QT import close [as 别名]

#.........这里部分代码省略.........
            functions.load_dataset(self.dispData, self.dicData, frequency_configuration)
            self.update_data_disp()

    def browse_saveMtx(self):
        savename = QFileDialog.getSaveFileName(self, "Select for 'base-name'+cII.mtx .. files")
        if savename:
            self.dispData['mtx '] = str(savename)
            logging.debug('Save .mtx:' + str(savename))
            self.saveMtx()

    def saveMtx(self):
        if self.dispData['mtx ']:
            savename = self.dispData['mtx ']
            res = self.dicData['res']  # this contains the calculation results
            logging.debug('Save .mtx:' + str(savename))
            on = self.dicData['hdf5_on']
            savemtx(savename + 'cII.mtx', np.expand_dims(res.IQmapM_avg[0], axis=0), on.headerII)
            savemtx(savename + 'cQQ.mtx', np.expand_dims(res.IQmapM_avg[1], axis=0), on.headerQQ)
            savemtx(savename + 'cIQ.mtx', np.expand_dims(res.IQmapM_avg[2], axis=0), on.headerIQ)
            savemtx(savename + 'cQI.mtx', np.expand_dims(res.IQmapM_avg[3], axis=0), on.headerQI)
            self.update_data_disp()

    def open_mtx_spyview(self):
        if self.dispData['mtx ']:
            d = threading.Thread(name='spyview', target=self._spyview)
            d.setDaemon(True)
            d.start()

    def _spyview(self):
        logging.debug('Spyview started')
        basen = self.dispData['mtx ']
        subprocess.call(['spyview', basen + 'cII.mtx', basen + 'cQQ.mtx',
                         basen + 'cIQ.mtx', basen + 'cQI.mtx'])
        logging.debug('Spyview closed')

    def read_table(self):
        table = self.tableWidget
        dD = self.dispData
        dD['f1'] = float(table.item(0, 0).text())
        dD['f2'] = float(table.item(1, 0).text())
        dD['g1'] = float(table.item(2, 0).text())
        dD['g2'] = float(table.item(3, 0).text())
        dD['B'] = float(table.item(4, 0).text())
        dD['select'] = int(eval(str(table.item(5, 0).text())))
        dD['lags'] = int(eval(str(table.item(6, 0).text())))
        dD['mapdim'][0] = int(table.item(7, 0).text())
        dD['mapdim'][1] = int(table.item(8, 0).text())
        dD['Phase correction'] = bool(eval(str(table.item(9, 0).text())))
        dD['Trigger correction'] = bool(eval(str(table.item(10, 0).text())))
        dD['FFT-Filter'] = bool(eval(str(table.item(11, 0).text())))
        dD['Power Averages'] = int(eval(str(table.item(12, 0).text())))
        dD['Low Pass'] = float(table.item(13, 0).text())
        dD['Averages'] = int(table.item(14, 0).text())
        dD['dim1 pt'] = int(table.item(15, 0).text())
        dD['dim1 start'] = float(table.item(16, 0).text())
        dD['dim1 stop'] = float(table.item(17, 0).text())
        dD['dim1 name'] = str(table.item(18, 0).text())
        dD['dim2 pt'] =  int(table.item(19, 0).text())
        dD['dim2 start'] = float(table.item(20, 0).text())
        dD['dim2 stop'] = float(table.item(21, 0).text())
        dD['dim2 name'] = str(table.item(22, 0).text())
        dD['dim3 pt'] = int(table.item(23, 0).text())
        dD['dim3 start'] = float(table.item(24, 0).text())
        dD['dim3 stop'] = float(table.item(25, 0).text())
        dD['dim3 name'] = str(table.item(26, 0).text())
        dD['Process Num'] = int(table.item(27, 0).text())
开发者ID:benschneider,项目名称:sideprojects1,代码行数:70,代码来源:start.py

示例6: Main

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QT import close [as 别名]
class Main(QMainWindow,Ui_MainWindow):
    def __init__(self,):
        super(Main,self).__init__()
        self.setupUi(self)
        
        self.actionLoad.triggered.connect(self.loadCfg)
        self.ReadButton.clicked.connect(self.readInData)
        self.UpdateButton.clicked.connect(self.updatePlot)
        self.TimeSlider.valueChanged.connect(self.updatePlot)
        self.TimeSlider.sliderMoved.connect(self.updateSlider)
        self.figs = []
        self.axs = []
        self.updating = False

        self.addmpl(Figure())

    def updateSlider(self):
        self.TimeDisplay.setText(self.strlist[self.TimeSlider.value()])

    def updatePlot(self):
        if not self.updating:
            self.updating = True
            self.rmmpl()
            self.addmpl(self.figs[self.TimeSlider.value()])
            self.updating = False

    def loadCfg(self):
        dlg = QFileDialog()
        dlg.setFilter("Config Files (*.ini)")
        self.inifn = str(dlg.getOpenFileName(self,'Open File','.','Config Files (*.ini)'))
        if(self.inifn):
            text = open(self.inifn,'r')
            self.ConfigBox.setText(text.read())
            text.close()

        #self.settings = QSettings(self.inifn, QSettings.IniFormat) #MAYBE USE QSETTINGS FOR INI READ/WRITE?!?!?

    def addmpl(self,fig):
        self.canvas = FigureCanvas(fig)
        self.mplvl.addWidget(self.canvas)
        self.canvas.draw()

        self.toolbar = NavigationToolbar(self.canvas,
                                         self.mplwindow,
                                         coordinates=True)
        self.addToolBar(self.toolbar)

    def rmmpl(self,):
        self.mplvl.removeWidget(self.canvas)
        self.canvas.close()
        self.mplvl.removeWidget(self.toolbar)
        self.toolbar.close()

    def readInData(self):
        f = open(self.inifn,'w')
        f.write(str(self.ConfigBox.toPlainText()))
        f.close()
        
        gpsloc = str(self.GPSBox.text())
        isrloc = str(self.ISRBox.text())
        asloc = str(self.AllSkyBox.text())
        self.PC = PlotClass(self.inifn,GPSloc=gpsloc,ASloc=asloc,ISRloc=isrloc)
        
        self.strlist = [insertinfo( str(j)+' $tmdy $thmsehms',posix=i[0],posixend=i[1]) for j, i in enumerate(self.PC.Regdict['Time'])]
        self.TimeSlider.setMaximum(len(self.strlist)-1)
        self.TimeSlider.setTracking(False)
        self.TimeSlider.setTickPosition(1)

        self.figs=[]
        self.axs=[]
        for t in range(len(self.strlist)):
            print(self.strlist[t])
            self.figs.append(Figure(figsize=(16,10)))
            self.axs.append(self.figs[t].add_subplot(111))
            m=self.PC.plotmap(self.figs[t],self.axs[t])
            (allhands,cbarsax)=self.PC.plotsingle(m,self.axs[t],self.figs[t],timenum=t,icase=0)
        self.rmmpl()
        self.addmpl(self.figs[0])
开发者ID:jswoboda,项目名称:MahaliPlotting,代码行数:80,代码来源:MahaliGui.py

示例7: Main

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QT import close [as 别名]

#.........这里部分代码省略.........
			self.paraLayout.addRow(self.delayLabel,self.delayLineEdit)
	def startSweep(self):
		self.onStart()

		# if self.modeComboBox.currentText == 'Voltage Sweep':
		# 	compliance = int(self.complianceLineEdit.getText())
		# 	start = int(self.startLineEdit.getText())
		# 	stop = int(self.stopLineEdit.getText())
		# 	step = int(self.stepLineEdit.getText())
		# 	pointsNum = (stop-start)/step + 1
		# 	i = self.instruMap.keys()[self.instruMap.values().index('2400')]
		# 	self.instruObj[i].write("*RST")  #restore GPIB default conditions
		# 	self.instruObj[i].write(":SOUR:FUNC VOLT") #source is voltage
		# 	self.instruObj[i].write(":SENS:FUNC 'CURR:DC") #sense is Current
		# 	self.instruObj[i].write(":SENS:CURR:PROT %d" % compliance) #voltage protection
		# 	self.instruObj[i].write(":SOUR:VOLT:START %f" % start)
		# 	self.instruObj[i].write(":SOUR:VOLT:STOP %f" % stop)
		# 	self.instruObj[i].write(":SOUR:VOLT:STEP %f" % step)
		# 	self.instruObj[i].write(":SOUR:VOLT:MODE SWE") # sweep mode
		# 	self.instruObj[i].write(":SOUR:SWE:RANGE AUTO") #auto source ranging
		# 	self.instruObj[i].write(":SOUR:SWE:SPAC LIN") #select linear staricase sweep
		# 	self.instruObj[i].write(":TRIG:COUNT %d" % pointsNum)
		# 	self.instruObj[i].write(":SOUR:DEL 0.1")
		# 	self.instruObj[i].write(":FORM:ELEM CURR")  #current reading only
		# 	self.instruObj[i].write(":OUTP ON")
		# 	self.instruObj[i].write(":READ?")
		# 	aa = self.instruObj[i].read()

	def onStart(self):
		self.x = []
		self.y = []
		self.canvas.axes.set_autoscalex_on(True)
		self.line, = self.canvas.axes.plot(self.x,self.y)
		timer = QtCore.QTimer(self)
		timer.timeout.connect(self.run)
		timer.start(10)
		#self.line, = self.canvas.axes.plot(self.x, self.y, animated=True, lw=2)
		#self.ani = animation.FuncAnimation(self.canvas.figure,self.run,self.data_gen, blit=True, interval = 100)
	# def data_gen(self):
	# 	while True:
	# 		self.p = -1*self.p
	# 		t = max(self.x) + 1
	# 		y = np.sin(t)
	# 		yield t,y
	def run(self):
		newx = max(self.x) + 1
		self.x.append(newx)
		self.y = np.sin(self.x)
		self.line.set_data(self.x, self.y)
		xmin,xmax = self.canvas.axes.get_xlim()
		ymin,ymax = self.canvas.axes.get_ylim()
		self.canvas.axes.figure.canvas.draw()
		if newx >= xmax:
			xmax = 2*xmax
			self.canvas.axes.set_xlim(0,xmax)
			self.canvas.axes.figure.canvas.draw()
			QtGui.qApp.processEvents()     #update the window to see the new x scale !important canvas.draw() must go before this line				
		self.tableWidget.insertRow(self.p)
		self.tableWidget.setItem(self.p,0,QtGui.QTableWidgetItem(datetime.now().strftime("%H:%M:%S.%f")))
		self.tableWidget.setItem(self.p,1,QtGui.QTableWidgetItem(str(newx)))
		self.tableWidget.setItem(self.p,2,QtGui.QTableWidgetItem(str(self.y[-1])))
		self.p += 1


		# newx, newy = data
		# self.x.append(newx)
		# self.y = np.sin(self.x)
		# self.line.set_data(self.x, self.y)
		# xmin,xmax = self.canvas.axes.get_xlim()
		# ymin,ymax = self.canvas.axes.get_ylim()
		# if newx >= xmax:
		# 	xmax = 2*xmax
		# 	self.canvas.axes.set_xlim(0,xmax)
		# 	self.canvas.axes.figure.canvas.draw()
		# 	QtGui.qApp.processEvents()     #update the window to see the new x scale !important canvas.draw() must go before this line		
		# return self.line,
		# self.fig_dict = {}
		# self.mplfigs.itemClicked.connect(self.addNumber)

	# def addNumber(self, item):
	# 	text = str(item.text())
	# 	self.rmmpl()
	# 	self.addmpl(self.fig_dict[text])

	# def addfig(self, name, fig):
	# 	self.fig_dict[name]  = fig
	# 	self.mplfigs.addItem(name)
	def init(self):
		self.x.append(1)
		self.x.append(2)
		self.y.append(4)
		self.y.append(-5)
		self.line.set_data(self.x, self.y)
		

	def rmmpl(self, ):
		self.mplvl.removeWidget(self.canvas)
		self.canvas.close()
		self.mplvl.removeWidget(self.toolbar)
		self.toolbar.close()
开发者ID:xiaomizhou,项目名称:Python_GUI,代码行数:104,代码来源:callMainWindow-v0.py

示例8: Main

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QT import close [as 别名]
class Main(QMainWindow, Ui_MainWindow):

    # Define plate arrays as global variables to be able use them elsewhere in the program.
    global w_plate
    global mx_plate
    global my_plate
    global qx_plate
    global qy_plate

    def __init__(self, ):
        super(Main, self).__init__()
        self.setupUi(self)

        self.btnPlot.setStyleSheet('color: red')
        self.textEdit.setTextColor(QtGui.QColor("magenta"))

        # Check deflections radio button by default
        self.deflections_radio.setChecked(False)

        # Creating a QButtonGroup and adding the plot options ratio buttons.
        # This will be used to make sure new results are plotted every time the solve button is pressed.
        # Otherwise, if the deflections radio button is already selected, new run won't plot results.
        self.group = QtGui.QButtonGroup()
        self.group.addButton(self.deflections_radio)
        self.group.addButton(self.mx_radio)
        self.group.addButton(self.my_radio)
        self.group.addButton(self.qx_radio)
        self.group.addButton(self.qy_radio)
        self.plot_options_group.setEnabled(False)

        self.infoLabel.setStyleSheet('color: blue')
        self.infoLabel.setText('  Theory of Plates and Shells\n' +
                               '  Süleyman Muti\n' +
                               '  Spring 2016')

        self.btnPlot.clicked.connect(lambda: self.fdm())
        self.deflections_radio.toggled.connect(lambda: self.deflections_radio_checked())
        self.mx_radio.toggled.connect(lambda: self.mx_radio_checked())
        self.my_radio.toggled.connect(lambda: self.my_radio_checked())
        self.qx_radio.toggled.connect(lambda: self.qx_radio_checked())
        self.qy_radio.toggled.connect(lambda: self.qy_radio_checked())

    def addmpl(self, fig):
        self.canvas = FigureCanvas(fig)
        self.mplvl.addWidget(self.canvas)
        self.canvas.draw()
        self.toolbar = NavigationToolbar(self.canvas,
                                         self.mplwindow, coordinates=True)
        self.mplvl.addWidget(self.toolbar)

    def rmmpl(self, ):
        self.mplvl.removeWidget(self.canvas)
        self.canvas.close()
        self.mplvl.removeWidget(self.toolbar)
        self.toolbar.close()

    def get_grid_size(self):
        if self.rBtn15x10.isChecked():
            return 15, 1e-6
        if self.rBtn30x20.isChecked():
            return 30, 1e-6
        elif self.rBtn180x120.isChecked():
            return 180, 1e-7
        elif self.rBtn540x360.isChecked():
            return 540, 1e-9

    def deflections_radio_checked(self):
        if self.deflections_radio.isChecked():
            self.rmmpl()
            self.print_plot(w_plate, 'Plate Deflections', 'viridis')

    def mx_radio_checked(self):
        if self.mx_radio.isChecked():
            self.rmmpl()
            self.print_plot(mx_plate, 'Mx Bending Moment', 'plasma')

    def my_radio_checked(self):
        if self.my_radio.isChecked():
            self.rmmpl()
            self.print_plot(my_plate, 'My Bending Moment', 'plasma')

    def qx_radio_checked(self):
        if self.qx_radio.isChecked():
            self.rmmpl()
            self.print_plot(qx_plate, 'Qx Transverse Shear Force', 'inferno')

    def qy_radio_checked(self):
        if self.qy_radio.isChecked():
            self.rmmpl()
            self.print_plot(qy_plate, 'Qy Transverse Shear Force', 'inferno')

    def print_plot(self, array_to_be_plotted, plot_title, colormap):
        a = array_to_be_plotted
        self.rmmpl()
        fig = Figure()
        self.addmpl(fig)
        ax = fig.add_subplot(111)
        cax = ax.imshow(a, cmap=colormap)
        fig.colorbar(cax, shrink=0.6, aspect=5)
        fig.tight_layout()
#.........这里部分代码省略.........
开发者ID:suleymanmuti,项目名称:python-plate-finite-difference,代码行数:103,代码来源:tps_hw.py

示例9: MainWindodw

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QT import close [as 别名]
class MainWindodw(QMainWindow, Ui_MainWindow):
    """main window of application"""
    def __init__(self):
        super(MainWindodw, self).__init__()
        self.setupUi(self)
        self.isTrigMode = False
        self.isRunMode = False
        self.button_list = [self.run_radio_button,
                            self.trig_radio_button,
                            self.run_push_button]
        self.data = []
        self.freq = []
        self.res = []

        # implement button's function
        self.trig_radio_button.clicked.connect(self.trig_toggled)
        self.run_radio_button.clicked.connect(self.run_toggled)
        self.run_push_button.clicked.connect(self.run_pushed)
        self.stop_push_button.clicked.connect(self.stop_pushed)
        self.saveraw_push_button.clicked.connect(self.saveraw_pushed)
        self.savefft_push_button.clicked.connect(self.savefft_pushed)

        # add empty plot
        fig1 = Figure()
        axfig1 = fig1.add_subplot(111)
        axfig1.plot()
        self.add_rawmpl(fig1)

        fig2 = Figure()
        axfig2 = fig2.add_subplot(111)
        axfig2.plot()
        self.add_fftmpl(fig2)

        thread = QtCore.QThread()
        self.reader = SerialReader()
        self.reader.moveToThread(thread)
        self.reader.sig_status.connect(self.serial_plot)
        self.reader.sig_termino.connect(self.enable_button)

    def add_rawmpl(self, fig):
        self.raw_canvas = FigureCanvas(fig)
        self.vl_raw.addWidget(self.raw_canvas)
        self.raw_canvas.draw()
        self.raw_toolbar = NavigationToolbar(self.raw_canvas,
            self, coordinates=True)
        self.vl_raw.addWidget(self.raw_toolbar)

    def add_fftmpl(self, fig):
        self.fft_canvas = FigureCanvas(fig)
        self.vl_fft.addWidget(self.fft_canvas)
        self.fft_canvas.draw()
        self.fft_toolbar = NavigationToolbar(self.fft_canvas,
            self, coordinates=True)
        self.vl_fft.addWidget(self.fft_toolbar)

    def remove_rawmpl(self):
        self.vl_raw.removeWidget(self.raw_canvas)
        self.raw_canvas.close()
        self.vl_raw.removeWidget(self.raw_toolbar)
        self.fft_toolbar.close()

    def remove_fftmpl(self):
        self.vl_fft.removeWidget(self.fft_canvas)
        self.fft_canvas.close()
        self.vl_fft.removeWidget(self.fft_toolbar)
        self.fft_toolbar.close()

    def trig_toggled(self):
        print('trig is toggled')
        self.isTrigMode = True
        self.isRunMode = False

    def run_toggled(self):
        print('run is toggled')
        self.isTrigMode = False
        self.isRunMode = True

    def run_pushed(self):
        if self.isTrigMode: self.reader.mode = b't'
        elif self.isRunMode: self.reader.mode = b'r'
        else:
            self.errorDialog('Select Mode')
            return
        self.disable_button()
        self.reader.run()
        time.sleep(5)

    def stop_pushed(self):
        self.reader.stop()
        self.reader.serial_close()

    def saveraw_pushed(self):
        if not self.data:
            self.errorDialog('No measurement')
            return
        filepath = QtGui.QFileDialog.getSaveFileName(filter='*.dat')[0]
        with open(filepath, 'w') as f:
            for item in self.data:
                f.write(str(item) + '\n')

#.........这里部分代码省略.........
开发者ID:hdkkato,项目名称:my_arduino_samples,代码行数:103,代码来源:serial_plot.py

示例10: Main

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QT import close [as 别名]

#.........这里部分代码省略.........
        elif plotType == '2D Image':
            headerList = ["Dep Var:", "Status:"]
            widgetTypeList = ["QLabel", "QCheckBox"]
            depVarList = [row[0] for row in self.dataChest.getVariables()[1]]
            if depVarName is None:
                depVarName = depVarList[0]
            for ii in range(0,len(headerList)):
                optionsSlice = QtGui.QVBoxLayout()
                label = QtGui.QLabel(self) # widget to log
                label.setText(headerList[ii])
                optionsSlice.addWidget(label)
                for depVar in depVarList:
                    if widgetTypeList[ii] =="QLabel":
                        label = QtGui.QLabel(self) # widget to log
                        label.setText(depVar)
                        optionsSlice.addWidget(label)
                    elif widgetTypeList[ii] =="QCheckBox":
                        checkBox = QtGui.QCheckBox('', self)  # widget to log
                        print "depVarName=", depVarName
                        if depVar == depVarName:
                            checkBox.setCheckState(QtCore.Qt.Checked)
                        checkBox.stateChanged.connect(partial(self.varStateChanged, depVar))
                        optionsSlice.addWidget(checkBox)
                optionsSlice.addStretch(1)
                self.scrollLayout.addLayout(optionsSlice)
            self.scrollLayout.addStretch(1)

    def clearLayout(self, layout):
        # Clear the plotType options layout and all widgets therein.
        for i in reversed(range(layout.count())):
            item = layout.itemAt(i)
            
            if isinstance(item, QtGui.QWidgetItem):
                item.widget().close()
            elif not isinstance(item, QtGui.QSpacerItem):
                self.clearLayout(item.layout())
            # remove the item from layout
            layout.removeItem(item) 

    def varStateChanged(self, name, state):
        # Add/remove variables from current displayed plot.
        if state == QtCore.Qt.Checked:
            self.varsToIgnore.remove(name)
            # Remove old figure, needs garbage collection too.
            self.removeFigFromCanvas()
            self.currentFig = self.figFromFileInfo(self.filePath,
                                                   self.fileName,
                                                   selectedPlotType=self.plotType,
                                                   varsToIgnore =self.varsToIgnore) 
            self.addFigureToCanvas(self.currentFig)
        else: # unchecked
            if name not in self.varsToIgnore:
                self.varsToIgnore.append(name)
            # Remove old figure, needs garbage collection too.
            self.removeFigFromCanvas()
            self.currentFig = self.figFromFileInfo(self.filePath,
                                                   self.fileName,
                                                   selectedPlotType=self.plotType,
                                                   varsToIgnore=self.varsToIgnore)
            self.updatePlotTypeOptions(self.plotType, '')
            self.addFigureToCanvas(self.currentFig)

    def convertPathToArray(self, path):
        if self.root + "/" in path:
            path = path.replace(self.root+"/", '')
        elif self.root in path:
开发者ID:McDermott-Group,项目名称:servers,代码行数:70,代码来源:grapher.py

示例11: Main

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QT import close [as 别名]

#.........这里部分代码省略.........
        try:
            self.rowEdit.setValue(int(self.data_dict[text].deviceRow))          
        except ValueError:
            pass
        try:
            self.powerType.setText(str(self.data_dict[text].laserPowerType))          
        except ValueError:
            pass
        try:
            self.powerValue.setText(str(self.data_dict[text].laserPower))          
        except ValueError:
            pass
        try:
            self.columnEdit.setValue(int(self.data_dict[text].deviceCol))          
        except ValueError:
            pass
        try:
            ind = self.deviceType.findText(str(self.data_dict[text].deviceType).strip())        
            self.deviceType.setCurrentIndex(ind)          
        except ValueError:
            pass           
        self.activefig=fig
        self.activeDataSet=self.data_dict[text]

    def addmpl(self, fig):
        self.canvas = FigureCanvas(fig)
        self.mplvl.addWidget(self.canvas)
        self.canvas.draw()
        self.toolbar = NavigationToolbar(self.canvas, self.mplwindow, coordinates=True)
        self.mplvl.addWidget(self.toolbar)
    
    def rmmpl(self,):
        self.mplvl.removeWidget(self.canvas)
        self.canvas.close()
        self.mplvl.removeWidget(self.toolbar)
        self.toolbar.close()
#        self.activefig.canvas.mpl_disconnect(self.cid)
    
#This has to be modified for data types other than a ZI data input
    def adddata(self, name, xyDataClass):
        self.data_dict[name] = xyDataClass
        self.mplfigs.addItem(name)
    
#Clcik on active MPL window    
    def onclick(self, event):
#        print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(event.button, event.x, event.y, event.xdata, event.ydata)
        print self.activeDataSet.find_nearestx(event.xdata)
#gca can get limits of zoomed widow
    def onFit(self,):
        self.disableForFit()
    
    def fitClick(self, event):
        self.cancelFit.setEnabled(True)
        print 'clicked'
        self.activefig.canvas.mpl_disconnect(self.cid)
        xi,xf = self.activeDataSet.fig.gca().get_xlim()
        xi, xvi = self.activeDataSet.find_nearestx(xi)
        xf, xvf = self.activeDataSet.find_nearestx(xf)
# General to this point, actual fit can vary below        
        x0 = event.xdata
        y0 = event.ydata        
        Q = float(self.QEntry.text())
        sigma=1/(2*Q)
        print xi,xf, [x0,y0,sigma]
        ip=[x0,y0,sigma]
        print self.activeDataSet
开发者ID:davidmiller3,项目名称:plotterGUI,代码行数:70,代码来源:custommpl.py

示例12: Main

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QT import close [as 别名]
class Main(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, ):
        super(Main, self).__init__()
        self.setupUi(self)
        self.PlotButton.clicked.connect(self.plot)
        self.ClearButton.clicked.connect(self.clear)
        self.SaveButton.clicked.connect(self.save)
        self.QuitButton.clicked.connect(self.quit)
        self.subjectNo = 0;
        self.filter = 0;
        self.param =0;
        self.fig = plt.figure();
        self.a1 = self.fig.add_subplot(121)
        self.a2 = self.fig.add_subplot(122)
        self.cnx = mysql.connector.connect(user='root',password='neuro',database='mohand');
        self.cursor = self.cnx.cursor();

    def addplot(self):
        self.canvas = FigureCanvas(self.fig)
        self.mplvl.addWidget(self.canvas)
        self.canvas.draw()
        self.toolbar = NavigationToolbar(self.canvas, self, coordinates=True)
        self.addToolBar(self.toolbar)

    def rmplot(self):
        self.mplvl.removeWidget(self.canvas)
        self.canvas.close()
        self.mplvl.removeWidget(self.toolbar)
        self.toolbar.close()

    def filterstr(self,x):
        return{
            0: '_fil_',
            1: '_raw_'
            }.get(x)

    def paramstr(self,x):
        return{
            0: 'indexVal',
            1: 'meanReactionTime',
            2: 'meanMovementTime',
            3: 'meanResponseTime',
            4: 'meanMaxVel',
            5: 'meanMaxAcc',
            6: 'meanEPD',
            7: 'meanRealDist',
            8: 'meanTraversedDist',
            9: 'meanPerDev',
            10: 'ovMaxReactionTime',
            11: 'ovMaxMovementTime',
            12: 'ovMaxEPD',
            13: 'ovMaxSpeed',
            14: 'ovMaxAcc'
        }.get(x)

    def daystr(self,x):
        return{
            0: 'baseline',
            1: 'day1',
            2: 'day2',
            3: 'day3',
            4: 'day4',
            5: 'day5'
            }.get(x,'performance')
    
    def plot(self):
        print "plotting graph";
        self.subjectNo = int(self.text_subNo.text());
        self.filter = self.combo_filter.currentIndex();
        self.param = self.combo_param.currentIndex();
        fstr = self.filterstr(self.filter);
        pstr = self.paramstr(self.param);
        rep_data = np.zeros(7);
        ran_data = np.zeros(7);
        for i in range(7):
            s = "select count("+pstr+fstr+"rep) from "+self.daystr(i)+" where subNo="+str(self.subjectNo);
            res=self.cursor.execute(s);
            if(int(self.cursor.fetchone()[0])==1):
                s = "select "+pstr+fstr+"rep from "+self.daystr(i)+" where subNo="+str(self.subjectNo);
                res2 = self.cursor.execute(s);
                rep_data[i] = float(self.cursor.fetchone()[0]);
            s = "select count("+pstr+fstr+"ran) from "+self.daystr(i)+" where subNo="+str(self.subjectNo);
            res=self.cursor.execute(s);
            if(int(self.cursor.fetchone()[0])==1):
                s = "select "+pstr+fstr+"ran from "+self.daystr(i)+" where subNo="+str(self.subjectNo);
                res2 = self.cursor.execute(s);
                ran_data[i] = float(self.cursor.fetchone()[0]);
        self.rmplot();
        
        labels = ['Baseline', 'Day 1', 'Day 2','Day 3','Day 4','Day 5','Performance'];
        self.a1.set_xticklabels(labels);
        self.a2.set_xticklabels(labels);
        self.a1.set_title('Repeated Sequence');
        self.a2.set_title('Random Sequence');
        label_ax = 'Subject '+str(self.subjectNo)+' '+pstr;
        self.a1.plot(rep_data, label=label_ax);
        self.a2.plot(ran_data, label =label_ax);
        leg1 = self.a1.legend(loc='best');
        leg2 = self.a2.legend(loc='best');
        leg1.draggable(state=True);
#.........这里部分代码省略.........
开发者ID:arnaghosh,项目名称:MITACS,代码行数:103,代码来源:plotter_prog.py

示例13: Main

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QT import close [as 别名]

#.........这里部分代码省略.........
        self.rho_h.setText('%3e' %(v_c.corr_h()) )
        
        self.allxpoints = self.tempxpt
        self.allypoints = self.tempypt

    def _reset(self):
        self.previous_point = []
        self.tempxpt,self.tempypt = [],[]
        self.allxpoints = []
        self.allypoints = []
        self.start_point = []
        self.end_point = []
        self.line = None

        ## remember to right-click before reset if changed frame
        self.ax.lines = []
        self.changefig(self.mplfigs.currentItem())

        self.xst.setValue(0)
        self.yst.setValue(0)
            
    def changefig(self, item):
        text = str(item.text())
        self.rmmpl()
        self.addmpl(self.fig_dict[text], self.fg_dict[text])

    def addmpl(self, fig, fg):
        self.canvas = FigureCanvas(fig)
        self.mplvl.addWidget(self.canvas)
        self.toolbar = NavigationToolbar(self.canvas,
                                         self.mplwindow, coordinates=True)
        self.mplvl.addWidget(self.toolbar)
        self.fg = fg
        
        self.ax = self.fig.add_subplot(111)
        self.canvas.draw()
        self.canvas.setFocusPolicy( Qt.ClickFocus )
        self.canvas.setFocus()
        self.canvas.mpl_connect('button_press_event', self.__button_press_callback)
        
    def rmmpl(self,):
        self.mplvl.removeWidget(self.canvas)
        self.canvas.close()
        self.mplvl.removeWidget(self.toolbar)
        self.toolbar.close()

    def __button_press_callback(self, event):
        if event.inaxes:
            x, y = event.xdata, event.ydata
            self.ax = event.inaxes
            if event.button == 1 and event.dblclick == False:  # If you press the left button, single click
                if self.line == None: # if there is no line, create a line
                    self.line = plt.Line2D([x, x],
                                           [y, y],
                                           marker='o',
                                           color=self.roicolor)
                    self.start_point = [x,y]
                    self.previous_point =  self.start_point
                    self.allxpoints=[x]
                    self.allypoints=[y]
                                                
                    self.ax.add_line(self.line)
                    self.canvas.draw()
                    # add a segment
                else: # if there is a line, create a segment
                    self.line = plt.Line2D([self.previous_point[0], x],
                                           [self.previous_point[1], y],
                                           marker = 'o',color=self.roicolor)
                    self.previous_point = [x,y]
                    self.allxpoints.append(x)
                    self.allypoints.append(y)
                                                                                
                    event.inaxes.add_line(self.line)
                    self.canvas.draw()
            elif ((event.button == 1 and event.dblclick==True) or
                  (event.button == 3 and event.dblclick==False)) and self.line != None: # close the loop and disconnect
                self.canvas.mpl_disconnect(self.__ID2) #joerg
                        
                self.line.set_data([self.previous_point[0],
                                    self.start_point[0]],
                                   [self.previous_point[1],
                                    self.start_point[1]])
                self.ax.add_line(self.line)
                self.canvas.draw()
                self.line = None
                                    
    def getMask(self, ci):
        ny, nx = ci.shape        
        poly_verts = [(self.allxpoints[0], self.allypoints[0])]
        for i in range(len(self.allxpoints)-1, -1, -1):
            poly_verts.append((self.allxpoints[i], self.allypoints[i]))
        
        x, y = np.meshgrid(np.arange(nx), np.arange(ny))
        x, y = x.flatten(), y.flatten()
        points = np.vstack((x,y)).T

        ROIpath = mplPath.Path(poly_verts)
        grid = ROIpath.contains_points(points).reshape((ny,nx))
        
        return grid
开发者ID:Mipanox,项目名称:Astroph,代码行数:104,代码来源:roi_vecr_sf.py


注:本文中的matplotlib.backends.backend_qt4agg.NavigationToolbar2QT.close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。