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


Python NavigationToolbar2QT.addAction方法代码示例

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


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

示例1: Plot

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QT import addAction [as 别名]
class Plot(object):
    def __init__(self, figure, identifier, filepath):
        loader = UiLoader()
        self.ui = loader.load('plot_window.ui', PlotWindow())

        # Tell Windows how to handle our windows in the the taskbar, making pinning work properly and stuff:
        if os.name == 'nt':
            self.ui.newWindow.connect(set_win_appusermodel)

        self.set_window_title(identifier, filepath)

        # figure.tight_layout()
        self.figure = figure
        self.canvas = FigureCanvas(figure)
        self.navigation_toolbar = NavigationToolbar(self.canvas, self.ui)

        self.lock_action = self.navigation_toolbar.addAction(
            QtGui.QIcon(':qtutils/fugue/lock-unlock'),
           'Lock axes', self.on_lock_axes_triggered)
        self.lock_action.setCheckable(True)
        self.lock_action.setToolTip('Lock axes')

        self.ui.verticalLayout_canvas.addWidget(self.canvas)
        self.ui.verticalLayout_navigation_toolbar.addWidget(self.navigation_toolbar)

        self.lock_axes = False
        self.axis_limits = None

        self.update_window_size()

        self.ui.show()

    def on_lock_axes_triggered(self):
        if self.lock_action.isChecked():
            self.lock_axes = True
            self.lock_action.setIcon(QtGui.QIcon(':qtutils/fugue/lock'))
        else:
            self.lock_axes = False
            self.lock_action.setIcon(QtGui.QIcon(':qtutils/fugue/lock-unlock'))

    @inmain_decorator()
    def save_axis_limits(self):
        axis_limits = {}
        for i, ax in enumerate(self.figure.axes):
            # Save the limits of the axes to restore them afterward:
            axis_limits[i] = ax.get_xlim(), ax.get_ylim()

        self.axis_limits = axis_limits

    @inmain_decorator()
    def clear(self):
        self.figure.clear()

    @inmain_decorator()
    def restore_axis_limits(self):
        for i, ax in enumerate(self.figure.axes):
            try:
                xlim, ylim = self.axis_limits[i]
                ax.set_xlim(xlim)
                ax.set_ylim(ylim)
            except KeyError:
                continue

    @inmain_decorator()
    def set_window_title(self, identifier, filepath):
        self.ui.setWindowTitle(str(identifier) + ' - ' + os.path.basename(filepath))

    @inmain_decorator()
    def update_window_size(self):
        l, w = self.figure.get_size_inches()
        dpi = self.figure.get_dpi()
        self.canvas.resize(int(l*dpi),int(w*dpi))
        self.ui.adjustSize()

    @inmain_decorator()
    def draw(self):
        self.canvas.draw()

    def show(self):
        self.ui.show()

    @property
    def is_shown(self):
        return self.ui.isVisible()
开发者ID:specialforcea,项目名称:labscriptsuite,代码行数:86,代码来源:analysis_subprocess.py

示例2: MatplotlibWidget

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QT import addAction [as 别名]
class MatplotlibWidget(QtGui.QWidget):
    """
    MatplotlibWidget is a plotting widget based on matplotlib.
    
    While the FigureCanvasQTAgg widget provided by matplotlib itself is
    intended for easy matplotlib integration in Qt applications, this
    widget focuses on hiding matplotlib internals from the user and
    adding new features.
    
    As the widget is designed to be used within applications,
    MatplotlibWidget provides methods for updating the data of
    graphs without clearing the figure and setting it up from scratch.
    This optimizes performance when the data is changed frequently.
    
    After creating a MatplotlibWidget, you add a new plots to the
    figure by calling :func:`addGroupedPlot`. A new feature is the
    use of so called `plot groups`. When calling :func:`newPlotGroup`,
    all subsequent calls to :func:`addGroupedPlot` will add new plots
    to a different group, which will change the appearance of the
    plots. The plot will be updated when calling :func:`draw`.
    
    All plots within a group will have the same color but different
    line styles. Each group however will differ in color. You can
    choose a split presentation, where each group will be displayed
    in its own graph.
    
    You can use :func:`updateGroupedPlot` for changing the plot-data,
    or :func:`clearPlots` for clearing the whole figure and setting
    it up from scratch.
    
    :param parent: Parent parameter of QWidget, usually None.
    :param autoscaleBn: (bool) Add autoscale button to panel.
    
    Example:
    
    .. literalinclude:: ../src/qao/gui/MatplotlibWidget.py
        :pyobject: testMatplotlibWidget
    """
    
    colors = 'bgrkcm'
    markers = 'os^vd'
    linestyles = ['-', '--', '-.', ':']

    def __init__(self, parent=None, autoscaleBn = False):
        QtGui.QWidget.__init__(self, parent)
        
        # canvas
        font = self.font()
        windowColor = str(self.palette().window().color().name())
        matplotlib.rc('font', family=str(font.family()), size=.9*font.pointSize(), weight="normal")
        matplotlib.rc('figure', facecolor=windowColor, edgecolor=windowColor)
        self.fig = Figure(dpi=self.logicalDpiX())
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)

        # navigation
        self.navigation = NavigationToolbar(self.canvas, self, coordinates=False)
        self.actionGroupPlotStyle = self.navigation.addAction("Split", self.toggleGroupPlotStyle)
        self.actionGroupPlotStyle.setCheckable(True)
        self.actionAutoscale = self.navigation.addAction("Auto", self.toggleAutoscale)
        self.actionAutoscale.setCheckable(True)
        self.actionAutoscale.setChecked(True)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.canvas)
        layout.addWidget(self.navigation)
        
        # init other stuff
        self.xlabel = ""
        self._needSetupFigure = True
        self._needSetupLines  = True
        self._needRescale     = True
        self.clearPlots()
        self.setGropPlotStyle("combined")
    
    def clearPlots(self):
        """
        Removes all plots from the figure and deletes all plot groups.
        """
        self.plotPointGroups = []
        self.plotLineGroups = []
        self._needSetupFigure = True
    
    def resizeEvent(self, event):
        if self.isMinimized() or self.isHidden(): return
        w, h = event.size().width(), event.size().height()
        self.fig.subplots_adjust(left = 30./w, right = 1-5./w, top = 1-5./h, bottom = 50./h, hspace = 70./h)
        
    def newPlotGroup(self):
        """
        Creates a new group for further plots added to the figure.
        
        Plots within a group have different line styles. Plots of different
        groups will receive different colors. In the split presentation, each
        plot group will be displayed in its own graph.
        
        :returns: (int) Group id assigned for updating plots later on.
        """
        assert len(self.plotPointGroups) < len(self.colors), "maximum number of plot groups reached"
        self.plotPointGroups.append([])
        self.plotLineGroups.append([])
#.........这里部分代码省略.........
开发者ID:pwuertz,项目名称:qao,代码行数:103,代码来源:MatplotlibWidget.py

示例3: BaseGui

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QT import addAction [as 别名]
class BaseGui(QtGui.QMainWindow):

    def __init__(self):

        # define the inheritance, nothing to QMainWindow
        super(BaseGui, self).__init__()

        # call the GUI init function and show
        self.initGUI()
        self.show()

    # initialize the GUI layout
    def initGUI(self, width = 600, height = 400):

        # resize, center, set window title and icon
        self.resize(width, height)
        self.center()
        self.setWindowTitle('Base QT GUI')
        self.setWindowIcon(QtGui.QIcon('pngs/wolf.png'))

        # set up status bar at bottom of application
        self.statusBar().showMessage('Ready')   # initialize statusbar

        # set up central widget
        self.cw = QtGui.QWidget()
        self.setCentralWidget(self.cw)

        # set up grid on central widget, a 10x10 grid is implied for now
        self.grid = QtGui.QGridLayout(self.cw)
        self.grid.setSpacing(6)

        # create a figure, canvas, and toolbar
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)

        # add the figure and toolbar to the central widget grid
        self.grid.addWidget(self.toolbar, 0, 0, 1, 9)
        self.grid.addWidget(self.canvas, 1, 0, 3, 9)

        # create a slider and LCD display, add to central widget, wire together
        self.slider = QtGui.QSlider(QtCore.Qt.Horizontal)
        self.lcd = QtGui.QLCDNumber()
        self.sLabel = QtGui.QLabel('Select\nFrequency')
        self.grid.addWidget(self.slider, 8, 1, 2, 8)
        self.grid.addWidget(self.lcd, 3, 9)
        self.grid.addWidget(self.sLabel, 8, 0)
        self.slider.valueChanged.connect(self.lcd.display)
        self.slider.valueChanged.connect(self.updatePlot)
        self.slider.setMaximum(30)

        # create quit pushbutton with tooltip
        self.quitButton = QtGui.QPushButton('Quit')
        self.quitButton.resize(self.quitButton.sizeHint())
        self.quitButton.setToolTip('Close This Application')
        self.quitButton.clicked.connect(QtGui.qApp.quit)
        self.grid.addWidget(self.quitButton, 9, 9)

        # add label and combo-box for type of plot for top subplot
        self.pLabelTop = QtGui.QLabel('Select Top Subplot Type')
        self.grid.addWidget(self.pLabelTop, 4, 0)
        self.pSelectTop = QtGui.QComboBox()
        self.pSelectTop.addItems(['', 'sin', 'cos', 'sin squared', 'cos squared'])
        self.grid.addWidget(self.pSelectTop, 4, 2, 1, 8)
        self.pSelectTop.activated[str].connect(self.updatePlot)

        # add label and combo-box for type of plot for bottom subplot
        self.pLabelBottom = QtGui.QLabel('Select Bottom Subplot Type')
        self.grid.addWidget(self.pLabelBottom, 5, 0)
        self.pSelectBottom = QtGui.QComboBox()
        self.pSelectBottom.addItems(['', 'sin', 'cos', 'sin squared', 'cos squared'])
        self.grid.addWidget(self.pSelectBottom, 5, 2, 1, 8)
        self.pSelectBottom.activated[str].connect(self.updatePlot)

        # add text edit box for number of data points in plot
        self.NpointsEdit = QtGui.QLineEdit('50')
        self.NpointsLabel = QtGui.QLabel('Set Number of Data Points in Plot')
        self.grid.addWidget(self.NpointsLabel, 0, 9)
        self.grid.addWidget(self.NpointsEdit, 1, 9)
        self.NpointsEdit.textChanged[str].connect(self.updatePlot)

        # create toolbar, add quit action to it
        self.toolbar = self.addToolBar('MainToolbar')
        exitAction = QtGui.QAction(QtGui.QIcon('pngs/quit.png'), 'Close Application', self)
        exitAction.triggered.connect(QtGui.qApp.quit)
        self.toolbar.addAction(exitAction)

    def updatePlot(self, text):

        # create axes in right place based on sender
        if self.sender() == self.pSelectTop:
            axes = [self.figure.add_subplot(2,1,1)]
        elif self.sender() == self.pSelectBottom:
            axes = [self.figure.add_subplot(2,1,2)]
        elif (self.sender() == self.slider) or (self.sender() == self.NpointsEdit):
            text = int()
            axes = []
            axes.append(self.figure.add_subplot(2,1,1))
            axes.append(self.figure.add_subplot(2,1,2))
        else:
#.........这里部分代码省略.........
开发者ID:russellburdt,项目名称:pyqt4,代码行数:103,代码来源:aliasing.py

示例4: plotting

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QT import addAction [as 别名]
class plotting(QtGui.QWidget):
    #for every 1D graph made , __init__, initUI , and graphRes is called.
    def __init__(self): #creation of the variables #initialized for all plotting instances
        #print('Plotting : init')
        super(plotting, self).__init__()
        self.initUI()

    def initUI(self): #initialized along with __init__
        #print('Plotting: initUI')
        self.figure=plt.figure()
        self.ax=self.figure.add_subplot(111)
        self.main_frame = QtGui.QTabWidget()
        
        
        self.canvas=FigureCanvas(self.figure)
        self.toolbar=NavigationToolbar(self.canvas,self.main_frame) #self.canvas
        self.canvas.setParent(self.main_frame) ##########
        #FigureCanvas.setPa
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.toolbar)
        vbox.addWidget(self.canvas)  # the matplotlib canvas
        self.main_frame.setLayout(vbox)
    
    def graphRes(self, data, calib=None): 

        #print('Plotting: graphRes') #ax = figure.add_subplot(111)
        self.ax.hold(True) #plot with the same axis parameters
        if calib==None: #object warning, still works, ignore for now
            #FutureWarning: comparison to `None` will result in an elementwise object comparison in the future.
            x= np.arange(0.,len(data))          
            self.ax.plot(x,data) #regular plot if no calibration data exists

        else:
            self.ax.plot(calib, data[:len(calib)]) #if calibration exists, use calibrated x axis data (calib), and y axis as regular procssed counts (data)

        #self.dc1=datacursor(formatter="Energy:{x:.4f}\nCounts:{y:.4f}".format,bbox=None) #interactive cursor , SLOW find alternative or fix
 
        #self.ax.imshow(data, interpolation='nearest') ##ADDED
        self.ax.xaxis.set_minor_locator(AutoMinorLocator()) #auto set minor ticks
        plt.tick_params(which='both', width=1)
        plt.tick_params(which='major', length=7)
        plt.tick_params(which='minor', length=4, color='r')
        self.ax.grid(True)
        self.canvas.draw() #draw in pyQT gui canvas rather than seperate window

    def graph2DRes(self, data): #3d plot
        print('Plotting: graph2DRes..Please wait...')
        #print('data from graph2dres is: ', data)
        #############################################
        #np.savetxt('2Dcoin.csv',data ,delimiter=",")#save 2D Data as CSV for later use
        #############################################        
        
        self.ax=self.figure.add_subplot(111) #, axisbg='slategray'
        self.ax.hold(False) #dont use same axis as before 
        gridsizes=int(max(np.amax(data[:,0]),np.amax(data[:,1]))) + 100 #set grid size to max of each channel total energy 
        print('2D plot gridsize is: ', gridsizes)
        #########Gridsize not working for HEXBIN graph option below, fix############
        #make 2D total counts external message module here (factoring in min count=2)
        totalgraphicalcounts = sum(data[:,2])
        print('the total (after 2count threshold) 2D coincidence counts are: ', totalgraphicalcounts)
        ######
        print('the maximum count at a point on the 2D coincidence graph is: ', np.amax(data[:,2])) #debugging purposes

        tdcm=self.ax.hexbin(data[:,0],data[:,1],C=(data[:,2]), gridsize=gridsizes, #tdcm= two dimensional color map
            cmap= cm.nipy_spectral, bins=None) #cmap = cm.viridis -> linear color scale
         
        self.figure.colorbar(tdcm) #gradient color bar , related to above tdcm parameters
        self.ax.grid(True)
        #self.dc1=datacursor(formatter="Energy:{x:.4f}\nCounts:{y:.4f}".format,bbox=None)
           #data cursor seems to be broken for 2d Graph
        self.canvas.draw() #draw 2D color map canvas
        
  
#==============================================================================
        #triple coincidence 3D plotting work in progress
#     def graph3DRes(self, data):
#         self.ax =self.figure.add_subplot(111, projection='3d')
#         self.ax.hold(False)
#         gridsize=int(max(np.amax(data[:,0]),np.amax(data[:,1])))
#         
#         tdcm=self.ax.scatter(data[:,0],data[:,1],C=(data[:,2]), gridsize=gridsize, cmap= plt.cm.nipy_spectral_r, bins=None)
#         self.figure.colorbar(tdcm)
#         
#         self.canvas.draw()
#==============================================================================

    def newButton(self, newAction):
        print('Plotting: newButton')
        self.toolbar.addAction(newAction)
开发者ID:ayuzer,项目名称:HC-Gammalyzer,代码行数:91,代码来源:plotting.py


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