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


Python Figure.get_size_inches方法代码示例

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


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

示例1: plotit

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_size_inches [as 别名]
def plotit( data, outfilename, **kargs ) :

    # going to make a 1 row x N column plot
    if len(data.shape)==1 : 
        num_rows = 1
    else : 
        num_rows = data.shape[1]

    # davep 02-Oct-2012 ; bump up the size to accommodate multiple rows
    fig = Figure()
    figsize = fig.get_size_inches()
#    fig.set_size_inches( (figsize[0],figsize[1]*num_rows) )

    if "title" in kargs : 
        fig.suptitle(kargs["title"])

    # http://matplotlib.org/faq/howto_faq.html
    # "Move the edge of an axes to make room for tick labels"
    # hspace is "the amount of height reserved for white space between
    # subplots"
    fig.subplots_adjust( hspace=0.40 )

    ax = fig.add_subplot(111)
    ax.grid()
    ax.set_ylim(-0.1,1.1)

    label_iter = iter( ("Strip Metric","FullPage Metric","All Strips' Mean"))
    for i in range(num_rows) : 
        if num_rows==1 :
            column = data 
        else : 
            column = data[ :, i ] 

        fmt = kargs.get("fmt","+")
        if "color" in kargs : 
            fmt += kargs["color"]            
        ax.plot(column,fmt,label=label_iter.next())

    if "axis_title" in kargs : 
        title = kargs["axis_title"][i]
        ax.set_title(title)

    ax.legend(loc="lower left")

    ax.set_xlabel( "Strip Number" )
    ax.set_ylabel( "Match Metric" )

    canvas = FigureCanvasAgg(fig)
    canvas.print_figure(outfilename)
    print "wrote", outfilename
开发者ID:Rventric,项目名称:page_segmentation,代码行数:52,代码来源:drawgraphs.py

示例2: plotit

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_size_inches [as 别名]
def plotit( data, outfilename, **kargs ) :

    # going to make a 1 row x N column plot
    if len(data.shape)==1 : 
        num_rows = 1
    else : 
        num_rows = data.shape[1]

    # davep 02-Oct-2012 ; bump up the size to accommodate multiple rows
    fig = Figure()
    figsize = fig.get_size_inches()
    fig.set_size_inches( (figsize[0],figsize[1]*num_rows) )

    if "title" in kargs : 
        fig.suptitle(kargs["title"])

    # http://matplotlib.org/faq/howto_faq.html
    # "Move the edge of an axes to make room for tick labels"
    # hspace is "the amount of height reserved for white space between
    # subplots"
    fig.subplots_adjust( hspace=0.40 )

    for i in range(num_rows) : 
        ax = fig.add_subplot(num_rows,1,i+1)
        ax.grid()
        if num_rows==1 :
            column = data 
        else : 
            column = data[ :, i ] 

        fmt = ""
        if "color" in kargs : 
            fmt += kargs["color"]            
        fmt += "+"
        ax.plot(column,fmt)

        if "axis_title" in kargs : 
            title = kargs["axis_title"][i]
            ax.set_title(title)

    canvas = FigureCanvasAgg(fig)
    canvas.print_figure(outfilename)
    print("wrote", outfilename)
开发者ID:linuxlizard,项目名称:pytools,代码行数:45,代码来源:plotdat.py

示例3: MyFrame

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_size_inches [as 别名]

#.........这里部分代码省略.........
        self.SetSizer(sizer_1)
        self.Layout()
        self.Centre()
        # end wxGlade
        # ~ self.dpi = 100
        # ~ self.fig = Figure((8.0, 20.0), dpi=self.dpi)
        # ~ self.canvas = FigCanvas(self.viewer, -1, self.fig)
        # ~ sizer_1.Add(self.frame_1_toolbar, 5, wx.LEFT | wx.EXPAND)
        # ~ self.redraw(event)
        # ~ self.axes = self.fig.add_subplot(111,axisbg='#ababab')

    def passdata(data):  # , samplerate, channellabels):
        import sys

        print sys.argv
        import getopt

        opts, extraparams = getopt.getopt(sys.argv[1:])
        # ~ data = np.random.randn(10000,10)
        # ~ self.origdata = data
        # ~ self.sr = np.float32(100.0)
        # ~ sp = 1/frame.sr
        # ~ self.timeaxes = np.arange(0,sp*1000, sp)
        # ~ self.chlabels = np.arange(0,244)

    def go(self, event):  # wxGlade: MyFrame.<event_handler>
        print "Event handler `go' "
        self.draw_figure(event)
        # self.redraw(event)

    def clear(self, event):  # wxGlade: MyFrame.<event_handler>
        print "Event handler `clear' not implemented"
        print self.GetSize()
        print self.fig.get_size_inches()
        x = self.canvas.GetClientSize()
        print x
        # self.canvas.SetClientSize((x[0]/2,x[1]/2))
        x = self.GetSize()
        self.canvas.SetClientSize((x[0] / 0.8, x[1] / 0.9))
        # self.canvas.Destroy()
        # self.fig.clear()

    def redraw(self, event):  # wxGlade: MyFrame.<event_handler>
        print "Event handler `redraw' not implemented"
        siz = self.GetSize()
        self.canvas.SetClientSize((siz[0] - 1, siz[1] - 100))
        self.canvas.Refresh(eraseBackground=True)

    def amplitudescale(self, event):  # wxGlade: MyFrame.<event_handler>
        print "Event handler `amwxplitudescale' not implemented"
        print self.slider_2.GetValue()
        dmin = self.origdata.min()
        dmax = self.origdata.max()
        print dmin, dmax
        self.step = abs(dmin + dmax / 10) / self.slider_2.GetValue()
        print "step2", self.step
        # self.go(event)
        # ~ self.numchans(event)
        # return step/self.slider_2.GetValue()
        # self.settimewin(event)

    def numchans(self, event):  # wxGlade: MyFrame.<event_handler>
        print "Event handler `numchans' not implemented"
        self.slider_1.SetRange(0, np.size(self.origdata, 1))
        self.data = self.origdata[:, 0 : self.slider_1.GetValue()]
        self.label2plot = self.chlabels[0 : self.slider_1.GetValue()]
开发者ID:neurodebian,项目名称:pymeg,代码行数:70,代码来源:megsubplot.py

示例4: HorizonFrame

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_size_inches [as 别名]

#.........这里部分代码省略.........
        self.createBatteryBar()

        # Create Mode & State Text
        self.createStateText()

        # Create Waypoint Text
        self.createWPText()

        # Create Waypoint Pointer
        self.createWPPointer()

        # Create Altitude History Plot
        self.createAltHistoryPlot()

        # Show Frame
        self.Show(True)
        self.pending = []

    def createPlotPanel(self):
        """Creates the figure and axes for the plotting panel."""
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.canvas.SetSize(wx.Size(300, 300))
        self.axes.axis("off")
        self.figure.subplots_adjust(left=0, right=1, top=1, bottom=0)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.EXPAND, wx.ALL)
        self.SetSizerAndFit(self.sizer)
        self.Fit()

    def rescaleX(self):
        """Rescales the horizontal axes to make the lengthscales equal."""
        self.ratio = self.figure.get_size_inches()[0] / float(self.figure.get_size_inches()[1])
        self.axes.set_xlim(-self.ratio, self.ratio)
        self.axes.set_ylim(-1, 1)

    def calcFontScaling(self):
        """Calculates the current font size and left position for the current window."""
        self.ypx = self.figure.get_size_inches()[1] * self.figure.dpi
        self.xpx = self.figure.get_size_inches()[0] * self.figure.dpi
        self.fontSize = self.vertSize * (self.ypx / 2.0)
        self.leftPos = self.axes.get_xlim()[0]
        self.rightPos = self.axes.get_xlim()[1]

    def checkReszie(self):
        """Checks if the window was resized."""
        if not self.resized:
            oldypx = self.ypx
            oldxpx = self.xpx
            self.ypx = self.figure.get_size_inches()[1] * self.figure.dpi
            self.xpx = self.figure.get_size_inches()[0] * self.figure.dpi
            if (oldypx != self.ypx) or (oldxpx != self.xpx):
                self.resized = True
            else:
                self.resized = False

    def createHeadingPointer(self):
        """Creates the pointer for the current heading."""
        self.headingTri = patches.RegularPolygon((0.0, 0.80), 3, 0.05, color="k", zorder=4)
        self.axes.add_patch(self.headingTri)
        self.headingText = self.axes.text(
            0.0,
            0.675,
            "0",
            color="k",
开发者ID:Dronecode,项目名称:MAVProxy,代码行数:70,代码来源:wxhorizon_ui.py

示例5: BackendMatplotlib

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_size_inches [as 别名]

#.........这里部分代码省略.........
        axes.set_ylabel(label)

    # Graph limits

    def resetZoom(self, dataMargins):
        xAuto = self._plot.isXAxisAutoScale()
        yAuto = self._plot.isYAxisAutoScale()

        if not xAuto and not yAuto:
            _logger.debug("Nothing to autoscale")
        else:  # Some axes to autoscale
            xLimits = self.getGraphXLimits()
            yLimits = self.getGraphYLimits(axis='left')
            y2Limits = self.getGraphYLimits(axis='right')

            # Get data range
            ranges = self._plot.getDataRange()
            xmin, xmax = (1., 100.) if ranges.x is None else ranges.x
            ymin, ymax = (1., 100.) if ranges.y is None else ranges.y
            if ranges.yright is None:
                ymin2, ymax2 = None, None
            else:
                ymin2, ymax2 = ranges.yright

            # Add margins around data inside the plot area
            newLimits = list(_utils.addMarginsToLimits(
                dataMargins,
                self.ax.get_xscale() == 'log',
                self.ax.get_yscale() == 'log',
                xmin, xmax, ymin, ymax, ymin2, ymax2))

            if self.isKeepDataAspectRatio():
                # Compute bbox wth figure aspect ratio
                figW, figH = self.fig.get_size_inches()
                figureRatio = figH / figW

                dataRatio = (ymax - ymin) / (xmax - xmin)
                if dataRatio < figureRatio:
                    # Increase y range
                    ycenter = 0.5 * (newLimits[3] + newLimits[2])
                    yrange = (xmax - xmin) * figureRatio
                    newLimits[2] = ycenter - 0.5 * yrange
                    newLimits[3] = ycenter + 0.5 * yrange

                elif dataRatio > figureRatio:
                    # Increase x range
                    xcenter = 0.5 * (newLimits[1] + newLimits[0])
                    xrange_ = (ymax - ymin) / figureRatio
                    newLimits[0] = xcenter - 0.5 * xrange_
                    newLimits[1] = xcenter + 0.5 * xrange_

            self.setLimits(*newLimits)

            if not xAuto and yAuto:
                self.setGraphXLimits(*xLimits)
            elif xAuto and not yAuto:
                if y2Limits is not None:
                    self.setGraphYLimits(
                        y2Limits[0], y2Limits[1], axis='right')
                if yLimits is not None:
                    self.setGraphYLimits(yLimits[0], yLimits[1], axis='left')

    def setLimits(self, xmin, xmax, ymin, ymax, y2min=None, y2max=None):
        # Let matplotlib taking care of keep aspect ratio if any
        self._dirtyLimits = True
        self.ax.set_xlim(min(xmin, xmax), max(xmin, xmax))
开发者ID:kif,项目名称:silx,代码行数:70,代码来源:BackendMatplotlib.py

示例6: MplView

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_size_inches [as 别名]
class MplView(FigureCanvas, BaseView):
    """
    Base class for matplotlib based views. This handles graph canvas setup, toolbar initialisation
    and figure save options. Subclass for your own graph-specific views.
    """
    is_floatable_view = True
    is_mpl_toolbar_enabled = True

    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
    def __init__(self, parent, width=5, height=4, dpi=100, **kwargs):

        self.v = parent

        self.fig = Figure(figsize=(width, height), dpi=dpi)
        self.ax = self.fig.add_subplot(111)
        
        self.ax.plot([1,2,3,4])

        self.ax.spines['top'].set_visible(False)
        self.ax.spines['right'].set_visible(False)
        self.ax.get_xaxis().tick_bottom()
        self.ax.get_yaxis().tick_left()

        FigureCanvas.__init__(self, self.fig)

        self.setParent(parent.views)

        FigureCanvas.setSizePolicy(self,
                                   QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
        
        # Install navigation handler; we need to provide a Qt interface that can handle multiple 
        # plots in a window under separate tabs
        self.navigation = MplNavigationHandler( self )
        

    def generate(self):
        pass

    def saveAsImage(self, settings): # Size, dots per metre (for print), resample (redraw) image
        filename, _ = QFileDialog.getSaveFileName(self, 'Save current figure', '',  "Tagged Image File Format (*.tif);;\
                                                                                     Portable Document File (*.pdf);;\
                                                                                     Encapsulated Postscript File (*.eps);;\
                                                                                     Scalable Vector Graphics (*.svg);;\
                                                                                     Portable Network Graphics (*.png)")

        if filename:
            size = settings.get_print_size('in')
            dpi = settings.get_dots_per_inch()
            prev_size = self.fig.get_size_inches()
            self.fig.set_size_inches(*size)
            
            self.fig.savefig(filename, dpi=dpi)
            self.fig.set_size_inches(*prev_size)
            self.redraw()
            
    def redraw(self):
        #FIXME: Ugly hack to refresh the canvas
        self.resize( self.size() - QSize(1,1) )
        self.resize( self.size() + QSize(1,1) )
        
    def resizeEvent(self,e):
        FigureCanvas.resizeEvent(self,e)
        

    def get_text_bbox_screen_coords(self, t):
        bbox = t.get_window_extent(self.get_renderer())        
        return bbox.get_points()

    def get_text_bbox_data_coords(self, t):
        bbox = t.get_window_extent(self.get_renderer())        
        axbox = bbox.transformed(self.ax.transData.inverted())
        return axbox.get_points()
        
    def extend_limits(self, a, b):
        # Extend a to meet b where applicable
        ax, ay = list(a[0]), list(a[1])
        bx, by = b[:,0], b[:,1]
   
        ax[0] = bx[0] if bx[0] < ax[0] else ax[0]
        ax[1] = bx[1] if bx[1] > ax[1] else ax[1]

        ay[0] = by[0] if by[0] < ay[0] else ay[0]
        ay[1] = by[1] if by[1] > ay[1] else ay[1]
                
        return [ax,ay]
开发者ID:pradal,项目名称:pathomx,代码行数:89,代码来源:views.py

示例7: PlotController

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_size_inches [as 别名]

#.........这里部分代码省略.........
        try:
            self.figure.canvas.draw()
            self.fix_after_drawing()
        except ParseFatalException:
            logger.exception("Caught unhandled exception when drawing")

    def fix_after_drawing(self):
        pass # nothing to fix

    # ------------------------------------------------------------
    #      Graph exporting
    # ------------------------------------------------------------
    def save(self, parent=None, suggest_name="graph", size="auto", num_specimens=1, offset=0.75):
        """
            Displays a save dialog to export an image from the current plot.
        """
        # Parse arguments:
        width, height = 0, 0
        if size == "auto":
            descr, width, height, dpi = settings.OUTPUT_PRESETS[0]
        else:
            width, height, dpi = map(float, size.replace("@", "x").split("x"))

        # Load gui:
        builder = gtk.Builder()
        builder.add_from_file(resource_filename("pyxrd.specimen", "glade/save_graph_size.glade")) # FIXME move this to this namespace!!
        size_expander = builder.get_object("size_expander")
        cmb_presets = builder.get_object("cmb_presets")

        # Setup combo with presets:
        cmb_store = gtk.ListStore(str, int, int, float)
        for row in settings.OUTPUT_PRESETS:
            cmb_store.append(row)
        cmb_presets.clear()
        cmb_presets.set_model(cmb_store)
        cell = gtk.CellRendererText()
        cmb_presets.pack_start(cell, True)
        cmb_presets.add_attribute(cell, 'text', 0)
        def on_cmb_changed(cmb, *args):
            itr = cmb_presets.get_active_iter()
            w, h, d = cmb_store.get(itr, 1, 2, 3)
            entry_w.set_text(str(w))
            entry_h.set_text(str(h))
            entry_dpi.set_text(str(d))
        cmb_presets.connect('changed', on_cmb_changed)

        # Setup input boxes:
        entry_w = builder.get_object("entry_width")
        entry_h = builder.get_object("entry_height")
        entry_dpi = builder.get_object("entry_dpi")
        entry_w.set_text(str(width))
        entry_h.set_text(str(height))
        entry_dpi.set_text(str(dpi))

        # What to do when the user wants to save this:
        def on_accept(dialog):
            # Get the selected file type and name:
            cur_fltr = dialog.get_filter()
            filename = dialog.get_filename()
            # Add the correct extension if not present yet:
            for fltr in self.file_filters:
                if cur_fltr.get_name() == fltr[0]:
                    if filename[len(filename) - 4:] != fltr[1][1:]:
                        filename = "%s%s" % (filename, fltr[1][1:])
                    break
            # Get the width, height & dpi
            width = float(entry_w.get_text())
            height = float(entry_h.get_text())
            dpi = float(entry_dpi.get_text())
            i_width, i_height = width / dpi, height / dpi
            # Save it all right!
            self.save_figure(filename, dpi, i_width, i_height)

        # Ask the user where, how and if he wants to save:
        self.run_save_dialog("Save Graph", on_accept, None, parent=parent, suggest_name=suggest_name, extra_widget=size_expander)

    def save_figure(self, filename, dpi, i_width, i_height):
        """
            Save the current plot
            
            Arguments:
             filename: the filename to save to (either .png, .pdf or .svg)
             dpi: Dots-Per-Inch resolution
             i_width: the width in inch
             i_height: the height in inch
        """
        # Get original settings:
        original_dpi = self.figure.get_dpi()
        original_width, original_height = self.figure.get_size_inches()
        # Set everything according to the user selection:
        self.figure.set_dpi(dpi)
        self.figure.set_size_inches((i_width, i_height))
        self.figure.canvas.draw() # replot
        bbox_inches = matplotlib.transforms.Bbox.from_bounds(0, 0, i_width, i_height)
        # Save the figure:
        self.figure.savefig(filename, dpi=dpi, bbox_inches=bbox_inches)
        # Put everything back the way it was:
        self.figure.set_dpi(original_dpi)
        self.figure.set_size_inches((original_width, original_height))
        self.figure.canvas.draw() # replot
开发者ID:claudioquaglia,项目名称:PyXRD,代码行数:104,代码来源:controllers.py

示例8: plotTableWindow

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_size_inches [as 别名]

#.........这里部分代码省略.........
                        print plabel, label
                        if str(plabel) == str(label):
                            xdata = l.get_xdata()
                            ydata = l.get_ydata()
                            xs = numpy.concatenate((xdata, [x]))

                            ys = numpy.concatenate((ydata, [y]))
                            l.set_xdata(xs)
                            l.set_ydata(ys)
                            self.fig.canvas.draw()
                            self.plots[str(plabel)].currentX = xs.tolist()
                            self.plots[str(plabel)].currentY = ys.tolist()

    def onpick(self, event):
        """
        When the onpick event is raised, this function delete the points picked by the user, 
        in case the "delete points" radio button is selected
        """
        if self.modifyPlotsBox.isChecked() and self.deletePointsRadio.isChecked():

            thisline = event.artist
            xdata = thisline.get_xdata()
            ydata = thisline.get_ydata()
            label = thisline.get_label()
            print "label", label

            x = event.mouseevent.xdata
            y = event.mouseevent.ydata
            if x == None or y == None:
                return

            dx = numpy.array(abs(x - xdata[event.ind]), dtype=float)
            dy = numpy.array(abs(y - ydata[event.ind]), dtype=float)
            canvasSize = self.fig.get_size_inches()
            rangeX = abs(self.axes.get_xlim()[1] - self.axes.get_xlim()[0])
            rangeY = abs(self.axes.get_ylim()[1] - self.axes.get_ylim()[0])
            # Calculating limit distance on X
            # The limit  distance will be 0.01 inch
            limX = (0.05 * rangeX) / canvasSize[0]
            # Calculating limit  distance on Y
            # The limit  distance will be 0.01 inch
            limY = (0.05 * rangeY) / canvasSize[1]

            distances = numpy.hypot(dx, dy)
            indmin = distances.argmin()
            distanX = dx[indmin]
            distanY = dy[indmin]

            if distanX < limX and distanY < limY and str(label) in self.plots.keys():
                ind = event.ind[indmin]
                x = numpy.delete(xdata, ind)
                y = numpy.delete(ydata, ind)
                thisline.set_xdata(x)
                thisline.set_ydata(y)
                self.plots[str(label)].currentX = x.tolist()
                self.plots[str(label)].currentY = y.tolist()
                self.saveButton.setEnabled(True)
                self.canvas.draw()

    def enablePosition(self, position):
        if position == 0:
            self.xposSpin.setEnabled(True)
            self.yposSpin.setEnabled(True)

        else:
            self.xposSpin.setEnabled(False)
开发者ID:CANUBE,项目名称:GUIPSY,代码行数:70,代码来源:plotTableWindow.py

示例9: MainPlotController

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_size_inches [as 别名]

#.........这里部分代码省略.........
                bboxes.append(bboxi)
        except (RuntimeError, ValueError):
            logger.exception("Caught unhandled exception when joining boundig boxes")
            return None # don't continue
        # this is the bbox that bounds all the bboxes, again in relative
        # figure coords
        if len(bboxes) > 0:
            bbox = transforms.Bbox.union(bboxes)
            return bbox
        else:
            return None

    # ------------------------------------------------------------
    #      Graph exporting
    # ------------------------------------------------------------
    def save(self, parent=None, current_name="graph", size="auto", num_specimens=1, offset=0.75):
        """
            Displays a save dialog to export an image from the current plot.
        """
        # Parse arguments:
        width, height = 0, 0
        if size == "auto":
            descr, width, height, dpi = settings.OUTPUT_PRESETS[0]
        else:
            width, height, dpi = list(map(float, size.replace("@", "x").split("x")))

        # Load gui:
        builder = Gtk.Builder()
        builder.add_from_file(resource_filename("pyxrd.specimen", "glade/save_graph_size.glade")) # FIXME move this to this namespace!!
        size_expander = builder.get_object("size_expander")
        cmb_presets = builder.get_object("cmb_presets")

        # Setup combo with presets:
        cmb_store = Gtk.ListStore(str, int, int, float)
        for row in settings.OUTPUT_PRESETS:
            cmb_store.append(row)
        cmb_presets.clear()
        cmb_presets.set_model(cmb_store)
        cell = Gtk.CellRendererText()
        cmb_presets.pack_start(cell, True)
        cmb_presets.add_attribute(cell, 'text', 0)
        def on_cmb_changed(cmb, *args):
            itr = cmb.get_active_iter()
            w, h, d = cmb_store.get(itr, 1, 2, 3)
            entry_w.set_text(str(w))
            entry_h.set_text(str(h))
            entry_dpi.set_text(str(d))
        cmb_presets.connect('changed', on_cmb_changed)

        # Setup input boxes:
        entry_w = builder.get_object("entry_width")
        entry_h = builder.get_object("entry_height")
        entry_dpi = builder.get_object("entry_dpi")
        entry_w.set_text(str(width))
        entry_h.set_text(str(height))
        entry_dpi.set_text(str(dpi))

        # What to do when the user wants to save this:
        def on_accept(dialog):
            # Get the width, height & dpi
            width = float(entry_w.get_text())
            height = float(entry_h.get_text())
            dpi = float(entry_dpi.get_text())
            i_width, i_height = width / dpi, height / dpi
            # Save it all right!
            self.save_figure(dialog.filename, dpi, i_width, i_height)

        # Ask the user where, how and if he wants to save:
        DialogFactory.get_save_dialog(
            "Save Graph", parent=parent,
            filters=self.file_filters, current_name=current_name,
            extra_widget=size_expander
        ).run(on_accept)

    def save_figure(self, filename, dpi, i_width, i_height):
        """
            Save the current plot
            
            Arguments:
             filename: the filename to save to (either .png, .pdf or .svg)
             dpi: Dots-Per-Inch resolution
             i_width: the width in inch
             i_height: the height in inch
        """
        # Get original settings:
        original_dpi = self.figure.get_dpi()
        original_width, original_height = self.figure.get_size_inches()
        # Set everything according to the user selection:
        self.figure.set_dpi(dpi)
        self.figure.set_size_inches((i_width, i_height))
        self.figure.canvas.draw() # replot
        bbox_inches = matplotlib.transforms.Bbox.from_bounds(0, 0, i_width, i_height)
        # Save the figure:
        self.figure.savefig(filename, dpi=dpi, bbox_inches=bbox_inches)
        # Put everything back the way it was:
        self.figure.set_dpi(original_dpi)
        self.figure.set_size_inches((original_width, original_height))
        self.figure.canvas.draw() # replot

    pass # end of class
开发者ID:mathijs-dumon,项目名称:PyXRD,代码行数:104,代码来源:controllers.py

示例10: Figure

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_size_inches [as 别名]
	return r


phi = numpy.linspace(0, 2 * numpy.pi, 1024)
m_init = 3
n1_init = 2
n2_init = 18
n3_init = 18


fig = Figure((6, 6), dpi = 80)
ax = fig.add_subplot(111, polar = True)

r = supershape_radius(phi, 1, 1, m_init, n1_init, n2_init, n3_init)
lines, = ax.plot(phi, r, lw = 3.)


win = Gtk.Window()
win.connect('delete-event', Gtk.main_quit)
win.set_title('SuperShape')

canvas = FigureCanvasGTK3Agg(fig)
w, h = fig.get_size_inches()
dpi_res = fig.get_dpi()
w, h = int(numpy.ceil(w * dpi_res)), int(numpy.ceil(h * dpi_res))
canvas.set_size_request(w, h)
win.add(canvas)

win.show_all()
Gtk.main()
开发者ID:moonbury,项目名称:pythonanywhere,代码行数:32,代码来源:gtk-supershape.py

示例11: __init__

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_size_inches [as 别名]
class TreeFigure:
    def __init__(self, root, relwidth=0.5, leafpad=1.5, name=None,
                 support=70.0, scaled=True, mark_named=True,
                 leaf_fontsize=10, branch_fontsize=10,
                 branch_width=1, branch_color="black",
                 highlight_support=True,
                 branchlabels=True, leaflabels=True, decorators=[],
                 xoff=0, yoff=0,
                 xlim=None, ylim=None,
                 height=None, width=None):
        self.root = root
        self.relwidth = relwidth
        self.leafpad = leafpad
        self.name = name
        self.support = support
        self.scaled = scaled
        self.mark_named = mark_named
        self.leaf_fontsize = leaf_fontsize
        self.branch_fontsize = branch_fontsize
        self.branch_width = branch_width
        self.branch_color = branch_color
        self.highlight_support = highlight_support
        self.branchlabels = branchlabels
        self.leaflabels = leaflabels
        self.decorators = decorators
        self.xoff = xoff
        self.yoff = yoff

        nleaves = len(root.leaves())
        self.dpi = 72.0
        h = height or (nleaves*self.leaf_fontsize*self.leafpad)/self.dpi
        self.height = h
        self.width = width or self.height*self.relwidth
        ## p = min(self.width, self.height)*0.1
        ## self.height += p
        ## self.width += p
        self.figure = Figure(figsize=(self.width, self.height), dpi=self.dpi)
        self.canvas = FigureCanvas(self.figure)
        self.axes = self.figure.add_axes(
            tree.TreePlot(self.figure, 1,1,1,
                          support=self.support,
                          scaled=self.scaled,
                          mark_named=self.mark_named,
                          leaf_fontsize=self.leaf_fontsize,
                          branch_fontsize=self.branch_fontsize,
                          branch_width=self.branch_width,
                          branch_color=self.branch_color,
                          highlight_support=self.highlight_support,
                          branchlabels=self.branchlabels,
                          leaflabels=self.leaflabels,
                          interactive=False,
                          decorators=self.decorators,
                          xoff=self.xoff, yoff=self.yoff,
                          name=self.name).plot_tree(self.root)
            )
        self.axes.spines["top"].set_visible(False)
        self.axes.spines["left"].set_visible(False)
        self.axes.spines["right"].set_visible(False)
        self.axes.spines["bottom"].set_smart_bounds(True)
        self.axes.xaxis.set_ticks_position("bottom")

        for v in self.axes.node2label.values():
            v.set_visible(True)

        ## for k, v in self.decorators:
        ##     func, args, kwargs = v
        ##     func(self.axes, *args, **kwargs)

        self.canvas.draw()
        ## self.axes.home()
        ## adjust_limits(self.axes)
        self.axes.set_position([0.05,0.05,0.95,0.95])

    @property
    def detail(self):
        return self.axes
        
    def savefig(self, fname):
        root, ext = os.path.splitext(fname)
        buf = tempfile.TemporaryFile()
        for i in range(3):
            self.figure.savefig(buf, format=ext[1:].lower())
            self.home()
            buf.seek(0)
        buf.close()
        self.figure.savefig(fname)

    def set_relative_width(self, relwidth):
        w, h = self.figure.get_size_inches()
        self.figure.set_figwidth(h*relwidth)

    def autoheight(self):
        "adjust figure height to show all leaf labels"
        nleaves = len(self.root.leaves())
        h = (nleaves*self.leaf_fontsize*self.leafpad)/self.dpi
        self.height = h
        self.figure.set_size_inches(self.width, self.height)
        self.axes.set_ylim(-2, nleaves+2)

    def home(self):
#.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:103,代码来源:

示例12: __init__

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_size_inches [as 别名]
class TreeFigure:
    def __init__(self, root, relwidth=0.5, leafpad=1.5, name=None,
                 support=70.0, scaled=True, mark_named=True,
                 leaf_fontsize=10, branch_fontsize=10,
                 branch_width=1, branch_color="black",
                 highlight_support=True,
                 branchlabels=True, leaflabels=True, decorators=[],
                 xoff=0, yoff=0,
                 xlim=None, ylim=None,
                 height=None, width=None):
        self.root = root
        self.relwidth = relwidth
        self.leafpad = leafpad
        self.name = name
        self.support = support
        self.scaled = scaled
        self.mark_named = mark_named
        self.leaf_fontsize = leaf_fontsize
        self.branch_fontsize = branch_fontsize
        self.branch_width = branch_width
        self.branch_color = branch_color
        self.highlight_support = highlight_support
        self.branchlabels = branchlabels
        self.leaflabels = leaflabels
        self.decorators = decorators
        self.xoff = xoff
        self.yoff = yoff

        nleaves = len(root.leaves())
        self.dpi = 72.0
        h = height or (nleaves*self.leaf_fontsize*self.leafpad)/self.dpi
        self.height = h
        self.width = width or self.height*self.relwidth
        ## p = min(self.width, self.height)*0.1
        ## self.height += p
        ## self.width += p
        self.figure = Figure(figsize=(self.width, self.height), dpi=self.dpi)
        self.canvas = FigureCanvas(self.figure)
        self.axes = self.figure.add_axes(
            tree.TreePlot(self.figure, 1,1,1,
                          support=self.support,
                          scaled=self.scaled,
                          mark_named=self.mark_named,
                          leaf_fontsize=self.leaf_fontsize,
                          branch_fontsize=self.branch_fontsize,
                          branch_width=self.branch_width,
                          branch_color=self.branch_color,
                          highlight_support=self.highlight_support,
                          branchlabels=self.branchlabels,
                          leaflabels=self.leaflabels,
                          interactive=False,
                          decorators=self.decorators,
                          xoff=self.xoff, yoff=self.yoff,
                          name=self.name).plot_tree(self.root)
            )
        self.axes.spines["top"].set_visible(False)
        self.axes.spines["left"].set_visible(False)
        self.axes.spines["right"].set_visible(False)
        self.axes.spines["bottom"].set_smart_bounds(True)
        self.axes.xaxis.set_ticks_position("bottom")

        for v in self.axes.node2label.values():
            v.set_visible(True)

        ## for k, v in self.decorators:
        ##     func, args, kwargs = v
        ##     func(self.axes, *args, **kwargs)

        self.canvas.draw()
        ## self.axes.home()
        ## adjust_limits(self.axes)
        self.axes.set_position([0.05,0.05,0.95,0.95])

    @property
    def detail(self):
        return self.axes
        
    def savefig(self, fname, format="pdf"):
        self.figure.savefig(fname, format = format)

    def set_relative_width(self, relwidth):
        w, h = self.figure.get_size_inches()
        self.figure.set_figwidth(h*relwidth)

    def autoheight(self):
        "adjust figure height to show all leaf labels"
        nleaves = len(self.root.leaves())
        h = (nleaves*self.leaf_fontsize*self.leafpad)/self.dpi
        self.height = h
        self.figure.set_size_inches(self.width, self.height)
        self.axes.set_ylim(-2, nleaves+2)

    def home(self):
        self.axes.home()
        
        
    def render_multipage(self, outfile, pagesize = [8.5, 11.0], 
                         dims = None, border = 0.393701, landscape = False):
        """
        Create a multi-page PDF document where the figure is cut into
#.........这里部分代码省略.........
开发者ID:ChriZiegler,项目名称:ivy,代码行数:103,代码来源:hardcopy.py


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