• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python cbook._warn_external函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中matplotlib.cbook._warn_external函数的典型用法代码示例。如果您正苦于以下问题:Python _warn_external函数的具体用法?Python _warn_external怎么用?Python _warn_external使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: __init__

 def __init__(self, toolmanager, name):
     cbook._warn_external(
         'The new Tool classes introduced in v1.5 are experimental; their '
         'API (including names) will likely change in future versions.')
     self._name = name
     self._toolmanager = toolmanager
     self._figure = None
开发者ID:HubertHolin,项目名称:matplotlib,代码行数:7,代码来源:backend_tools.py


示例2: __init__

    def __init__(self, figure, fh, dummy=False):
        """
        Creates a new PGF renderer that translates any drawing instruction
        into text commands to be interpreted in a latex pgfpicture environment.

        Attributes
        ----------
        figure : `matplotlib.figure.Figure`
            Matplotlib figure to initialize height, width and dpi from.
        fh : file-like
            File handle for the output of the drawing commands.
        """

        RendererBase.__init__(self)
        self.dpi = figure.dpi
        self.fh = fh
        self.figure = figure
        self.image_counter = 0

        # get LatexManager instance
        self.latexManager = LatexManager._get_cached_or_new()

        if dummy:
            # dummy==True deactivate all methods
            for m in RendererPgf.__dict__:
                if m.startswith("draw_"):
                    self.__dict__[m] = lambda *args, **kwargs: None
        else:
            # if fh does not belong to a filename, deactivate draw_image
            if not hasattr(fh, 'name') or not os.path.exists(fh.name):
                cbook._warn_external("streamed pgf-code does not support "
                                     "raster graphics, consider using the "
                                     "pgf-to-pdf option", UserWarning)
                self.__dict__["draw_image"] = lambda *args, **kwargs: None
开发者ID:QuLogic,项目名称:matplotlib,代码行数:34,代码来源:backend_pgf.py


示例3: tight_layout

    def tight_layout(self, figure, renderer=None,
                     pad=1.08, h_pad=None, w_pad=None, rect=None):
        """
        Adjust subplot parameters to give specified padding.

        Parameters
        ----------

        pad : float
            Padding between the figure edge and the edges of subplots, as a
            fraction of the font-size.
        h_pad, w_pad : float, optional
            Padding (height/width) between edges of adjacent subplots.
            Defaults to ``pad_inches``.
        rect : tuple of 4 floats, optional
            (left, bottom, right, top) rectangle in normalized figure
            coordinates that the whole subplots area (including labels) will
            fit into.  Default is (0, 0, 1, 1).
        """

        subplotspec_list = tight_layout.get_subplotspec_list(
            figure.axes, grid_spec=self)
        if None in subplotspec_list:
            cbook._warn_external("This figure includes Axes that are not "
                                 "compatible with tight_layout, so results "
                                 "might be incorrect.")

        if renderer is None:
            renderer = tight_layout.get_renderer(figure)

        kwargs = tight_layout.get_tight_layout_figure(
            figure, figure.axes, subplotspec_list, renderer,
            pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
        if kwargs:
            self.update(**kwargs)
开发者ID:jklymak,项目名称:matplotlib,代码行数:35,代码来源:gridspec.py


示例4: test_warn_external_frame_embedded_python

def test_warn_external_frame_embedded_python():
    with patch.object(cbook, "sys") as mock_sys:
        mock_sys._getframe = Mock(return_value=None)
        with warnings.catch_warnings(record=True) as w:
            cbook._warn_external("dummy")
    assert len(w) == 1
    assert str(w[0].message) == "dummy"
开发者ID:HubertHolin,项目名称:matplotlib,代码行数:7,代码来源:test_cbook.py


示例5: to_qcolor

def to_qcolor(color):
    """Create a QColor from a matplotlib color"""
    qcolor = QtGui.QColor()
    try:
        rgba = mcolors.to_rgba(color)
    except ValueError:
        cbook._warn_external('Ignoring invalid color %r' % color)
        return qcolor  # return invalid QColor
    qcolor.setRgbF(*rgba)
    return qcolor
开发者ID:HubertHolin,项目名称:matplotlib,代码行数:10,代码来源:_formlayout.py


示例6: add_tool

    def add_tool(self, name, tool, *args, **kwargs):
        """
        Add *tool* to `ToolManager`.

        If successful, adds a new event ``tool_trigger_{name}`` where
        ``{name}`` is the *name* of the tool; the event is fired everytime the
        tool is triggered.

        Parameters
        ----------
        name : str
            Name of the tool, treated as the ID, has to be unique.
        tool : class_like, i.e. str or type
            Reference to find the class of the Tool to added.

        Notes
        -----
        args and kwargs get passed directly to the tools constructor.

        See Also
        --------
        matplotlib.backend_tools.ToolBase : The base class for tools.
        """

        tool_cls = self._get_cls_to_instantiate(tool)
        if not tool_cls:
            raise ValueError('Impossible to find class for %s' % str(tool))

        if name in self._tools:
            cbook._warn_external('A "Tool class" with the same name already '
                                 'exists, not added')
            return self._tools[name]

        tool_obj = tool_cls(self, name, *args, **kwargs)
        self._tools[name] = tool_obj

        if tool_cls.default_keymap is not None:
            self.update_keymap(name, tool_cls.default_keymap)

        # For toggle tools init the radio_group in self._toggled
        if isinstance(tool_obj, tools.ToolToggleBase):
            # None group is not mutually exclusive, a set is used to keep track
            # of all toggled tools in this group
            if tool_obj.radio_group is None:
                self._toggled.setdefault(None, set())
            else:
                self._toggled.setdefault(tool_obj.radio_group, None)

            # If initially toggled
            if tool_obj.toggled:
                self._handle_toggle(tool_obj, None, None, None)
        tool_obj.set_figure(self.figure)

        self._tool_added_event(tool_obj)
        return tool_obj
开发者ID:QuLogic,项目名称:matplotlib,代码行数:55,代码来源:backend_managers.py


示例7: _remove_blacklisted_style_params

def _remove_blacklisted_style_params(d, warn=True):
    o = {}
    for key, val in d.items():
        if key in STYLE_BLACKLIST:
            if warn:
                cbook._warn_external(
                    "Style includes a parameter, '{0}', that is not related "
                    "to style.  Ignoring".format(key))
        else:
            o[key] = val
    return o
开发者ID:HubertHolin,项目名称:matplotlib,代码行数:11,代码来源:core.py


示例8: _parse_legend_args

def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
    """
    Get the handles and labels from the calls to either ``figure.legend``
    or ``axes.legend``.

    ``axs`` is a list of axes (to get legend artists from)
    """
    log = logging.getLogger(__name__)

    handlers = kwargs.get('handler_map', {}) or {}
    extra_args = ()

    if (handles is not None or labels is not None) and args:
        cbook._warn_external("You have mixed positional and keyword "
                             "arguments, some input may be discarded.")

    # if got both handles and labels as kwargs, make same length
    if handles and labels:
        handles, labels = zip(*zip(handles, labels))

    elif handles is not None and labels is None:
        labels = [handle.get_label() for handle in handles]

    elif labels is not None and handles is None:
        # Get as many handles as there are labels.
        handles = [handle for handle, label
                   in zip(_get_legend_handles(axs, handlers), labels)]

    # No arguments - automatically detect labels and handles.
    elif len(args) == 0:
        handles, labels = _get_legend_handles_labels(axs, handlers)
        if not handles:
            log.warning('No handles with labels found to put in legend.')

    # One argument. User defined labels - automatic handle detection.
    elif len(args) == 1:
        labels, = args
        # Get as many handles as there are labels.
        handles = [handle for handle, label
                   in zip(_get_legend_handles(axs, handlers), labels)]

    # Two arguments:
    #   * user defined handles and labels
    elif len(args) >= 2:
        handles, labels = args[:2]
        extra_args = args[2:]

    else:
        raise TypeError('Invalid arguments to legend.')

    return handles, labels, extra_args, kwargs
开发者ID:jklymak,项目名称:matplotlib,代码行数:51,代码来源:legend.py


示例9: get_renderer

def get_renderer(fig):
    if fig._cachedRenderer:
        renderer = fig._cachedRenderer
    else:
        canvas = fig.canvas

        if canvas and hasattr(canvas, "get_renderer"):
            renderer = canvas.get_renderer()
        else:
            # not sure if this can happen
            cbook._warn_external("tight_layout : falling back to Agg renderer")
            from matplotlib.backends.backend_agg import FigureCanvasAgg
            canvas = FigureCanvasAgg(fig)
            renderer = canvas.get_renderer()

    return renderer
开发者ID:QuLogic,项目名称:matplotlib,代码行数:16,代码来源:tight_layout.py


示例10: latex2png

def latex2png(latex, filename, fontset='cm'):
    latex = "$%s$" % latex
    orig_fontset = rcParams['mathtext.fontset']
    rcParams['mathtext.fontset'] = fontset
    if os.path.exists(filename):
        depth = mathtext_parser.get_depth(latex, dpi=100)
    else:
        try:
            depth = mathtext_parser.to_png(filename, latex, dpi=100)
        except Exception:
            cbook._warn_external("Could not render math expression %s" % latex,
                                 Warning)
            depth = 0
    rcParams['mathtext.fontset'] = orig_fontset
    sys.stdout.write("#")
    sys.stdout.flush()
    return depth
开发者ID:HubertHolin,项目名称:matplotlib,代码行数:17,代码来源:mathmpl.py


示例11: new_floating_axis

    def new_floating_axis(self, nth_coord, value,
                          axis_direction="bottom",
                          axes=None,
                          ):

        if axes is None:
            cbook._warn_external(
                "'new_floating_axis' explicitly requires the axes keyword.")
            axes = self.axes

        _helper = AxisArtistHelperRectlinear.Floating(
            axes, nth_coord, value, axis_direction)

        axisline = AxisArtist(axes, _helper)

        axisline.line.set_clip_on(True)
        axisline.line.set_clip_box(axisline.axes.bbox)
        return axisline
开发者ID:phobson,项目名称:matplotlib,代码行数:18,代码来源:axislines.py


示例12: _find_best_position

    def _find_best_position(self, width, height, renderer, consider=None):
        """
        Determine the best location to place the legend.

        *consider* is a list of ``(x, y)`` pairs to consider as a potential
        lower-left corner of the legend. All are display coords.
        """
        # should always hold because function is only called internally
        assert self.isaxes

        verts, bboxes, lines, offsets = self._auto_legend_data()
        if self._loc_used_default and verts.shape[0] > 200000:
            # this size results in a 3+ second render time on a good machine
            cbook._warn_external(
                'Creating legend with loc="best" can be slow with large '
                'amounts of data.'
            )

        bbox = Bbox.from_bounds(0, 0, width, height)
        if consider is None:
            consider = [self._get_anchored_bbox(x, bbox,
                                                self.get_bbox_to_anchor(),
                                                renderer)
                        for x in range(1, len(self.codes))]

        candidates = []
        for idx, (l, b) in enumerate(consider):
            legendBox = Bbox.from_bounds(l, b, width, height)
            badness = 0
            # XXX TODO: If markers are present, it would be good to
            # take them into account when checking vertex overlaps in
            # the next line.
            badness = (legendBox.count_contains(verts)
                       + legendBox.count_contains(offsets)
                       + legendBox.count_overlaps(bboxes)
                       + sum(line.intersects_bbox(legendBox, filled=False)
                             for line in lines))
            if badness == 0:
                return l, b
            # Include the index to favor lower codes in case of a tie.
            candidates.append((badness, idx, (l, b)))

        _, _, (l, b) = min(candidates)
        return l, b
开发者ID:jklymak,项目名称:matplotlib,代码行数:44,代码来源:legend.py


示例13: get_tool

    def get_tool(self, name, warn=True):
        """
        Return the tool object, also accepts the actual tool for convenience.

        Parameters
        ----------
        name : str, ToolBase
            Name of the tool, or the tool itself
        warn : bool, optional
            If this method should give warnings.
        """
        if isinstance(name, tools.ToolBase) and name.name in self._tools:
            return name
        if name not in self._tools:
            if warn:
                cbook._warn_external("ToolManager does not control tool "
                                     "%s" % name)
            return None
        return self._tools[name]
开发者ID:QuLogic,项目名称:matplotlib,代码行数:19,代码来源:backend_managers.py


示例14: new_fixed_axis

    def new_fixed_axis(self, loc,
                       nth_coord=None,
                       axis_direction=None,
                       offset=None,
                       axes=None,
                       ):

        if axes is None:
            cbook._warn_external(
                "'new_fixed_axis' explicitly requires the axes keyword.")
            axes = self.axes

        _helper = AxisArtistHelperRectlinear.Fixed(axes, loc, nth_coord)

        if axis_direction is None:
            axis_direction = loc
        axisline = AxisArtist(axes, _helper, offset=offset,
                              axis_direction=axis_direction,
                              )

        return axisline
开发者ID:phobson,项目名称:matplotlib,代码行数:21,代码来源:axislines.py


示例15: update_keymap

    def update_keymap(self, name, *keys):
        """
        Set the keymap to associate with the specified tool.

        Parameters
        ----------
        name : string
            Name of the Tool
        keys : keys to associate with the Tool
        """

        if name not in self._tools:
            raise KeyError('%s not in Tools' % name)

        self._remove_keys(name)

        for key in keys:
            for k in validate_stringlist(key):
                if k in self._keys:
                    cbook._warn_external('Key %s changed from %s to %s' %
                                         (k, self._keys[k], name))
                self._keys[k] = name
开发者ID:QuLogic,项目名称:matplotlib,代码行数:22,代码来源:backend_managers.py


示例16: inset_axes


#.........这里部分代码省略.........
        neither *bbox_to_anchor* nor *bbox_transform* are specified, those
        are relative to the parent_axes. Otherwise they are to be understood
        relative to the bounding box provided via *bbox_to_anchor*.

    loc : int or string, optional, default to 1
        Location to place the inset axes. The valid locations are::

            'upper right'  : 1,
            'upper left'   : 2,
            'lower left'   : 3,
            'lower right'  : 4,
            'right'        : 5,
            'center left'  : 6,
            'center right' : 7,
            'lower center' : 8,
            'upper center' : 9,
            'center'       : 10

    bbox_to_anchor : tuple or `matplotlib.transforms.BboxBase`, optional
        Bbox that the inset axes will be anchored to. If None,
        a tuple of (0, 0, 1, 1) is used if *bbox_transform* is set
        to *parent_axes.transAxes* or *parent_axes.figure.transFigure*.
        Otherwise, *parent_axes.bbox* is used. If a tuple, can be either
        [left, bottom, width, height], or [left, bottom].
        If the kwargs *width* and/or *height* are specified in relative units,
        the 2-tuple [left, bottom] cannot be used. Note that,
        unless *bbox_transform* is set, the units of the bounding box
        are interpreted in the pixel coordinate. When using *bbox_to_anchor*
        with tuple, it almost always makes sense to also specify
        a *bbox_transform*. This might often be the axes transform
        *parent_axes.transAxes*.

    bbox_transform : `matplotlib.transforms.Transform`, optional
        Transformation for the bbox that contains the inset axes.
        If None, a `.transforms.IdentityTransform` is used. The value
        of *bbox_to_anchor* (or the return value of its get_points method)
        is transformed by the *bbox_transform* and then interpreted
        as points in the pixel coordinate (which is dpi dependent).
        You may provide *bbox_to_anchor* in some normalized coordinate,
        and give an appropriate transform (e.g., *parent_axes.transAxes*).

    axes_class : `matplotlib.axes.Axes` type, optional
        If specified, the inset axes created will be created with this class's
        constructor.

    axes_kwargs : dict, optional
        Keyworded arguments to pass to the constructor of the inset axes.
        Valid arguments include:
        %(Axes)s

    borderpad : float, optional
        Padding between inset axes and the bbox_to_anchor. Defaults to 0.5.
        The units are axes font size, i.e. for a default font size of 10 points
        *borderpad = 0.5* is equivalent to a padding of 5 points.

    Returns
    -------
    inset_axes : `axes_class`
        Inset axes object created.
    """

    if axes_class is None:
        axes_class = HostAxes

    if axes_kwargs is None:
        inset_axes = axes_class(parent_axes.figure, parent_axes.get_position())
    else:
        inset_axes = axes_class(parent_axes.figure, parent_axes.get_position(),
                                **axes_kwargs)

    if bbox_transform in [parent_axes.transAxes,
                          parent_axes.figure.transFigure]:
        if bbox_to_anchor is None:
            cbook._warn_external("Using the axes or figure transform "
                                 "requires a bounding box in the respective "
                                 "coordinates. "
                                 "Using bbox_to_anchor=(0,0,1,1) now.")
            bbox_to_anchor = (0, 0, 1, 1)

    if bbox_to_anchor is None:
        bbox_to_anchor = parent_axes.bbox

    if isinstance(bbox_to_anchor, tuple) and \
        (isinstance(width, str) or isinstance(height, str)):
        if len(bbox_to_anchor) != 4:
            raise ValueError("Using relative units for width or height "
                             "requires to provide a 4-tuple or a "
                             "`BBox` instance to `bbox_to_anchor.")

    axes_locator = AnchoredSizeLocator(bbox_to_anchor,
                                       width, height,
                                       loc=loc,
                                       bbox_transform=bbox_transform,
                                       borderpad=borderpad)

    inset_axes.set_axes_locator(axes_locator)

    _add_inset_axes(parent_axes, inset_axes)

    return inset_axes
开发者ID:HubertHolin,项目名称:matplotlib,代码行数:101,代码来源:inset_locator.py


示例17: get_tight_layout_figure

def get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer,
                            pad=1.08, h_pad=None, w_pad=None, rect=None):
    """
    Return subplot parameters for tight-layouted-figure with specified padding.

    Parameters
    ----------
    fig : Figure
    axes_list : list of Axes
    subplotspec_list : list of `.SubplotSpec`
        The subplotspecs of each axes.
    renderer : renderer
    pad : float
        Padding between the figure edge and the edges of subplots, as a
        fraction of the font size.
    h_pad, w_pad : float
        Padding (height/width) between edges of adjacent subplots.  Defaults to
        *pad_inches*.
    rect : Tuple[float, float, float, float], optional
        (left, bottom, right, top) rectangle in normalized figure coordinates
        that the whole subplots area (including labels) will fit into.
        Defaults to using the entire figure.

    Returns
    -------
    subplotspec or None
        subplotspec kwargs to be passed to `.Figure.subplots_adjust` or
        None if tight_layout could not be accomplished.

    """

    subplot_list = []
    nrows_list = []
    ncols_list = []
    ax_bbox_list = []

    # Multiple axes can share same subplot_interface (e.g., axes_grid1); thus
    # we need to join them together.
    subplot_dict = {}

    subplotspec_list2 = []

    for ax, subplotspec in zip(axes_list, subplotspec_list):
        if subplotspec is None:
            continue

        subplots = subplot_dict.setdefault(subplotspec, [])

        if not subplots:
            myrows, mycols, _, _ = subplotspec.get_geometry()
            nrows_list.append(myrows)
            ncols_list.append(mycols)
            subplotspec_list2.append(subplotspec)
            subplot_list.append(subplots)
            ax_bbox_list.append(subplotspec.get_position(fig))

        subplots.append(ax)

    if len(nrows_list) == 0 or len(ncols_list) == 0:
        return {}

    max_nrows = max(nrows_list)
    max_ncols = max(ncols_list)

    num1num2_list = []
    for subplotspec in subplotspec_list2:
        rows, cols, num1, num2 = subplotspec.get_geometry()
        div_row, mod_row = divmod(max_nrows, rows)
        div_col, mod_col = divmod(max_ncols, cols)
        if mod_row != 0:
            cbook._warn_external('tight_layout not applied: number of rows '
                                 'in subplot specifications must be '
                                 'multiples of one another.')
            return {}
        if mod_col != 0:
            cbook._warn_external('tight_layout not applied: number of '
                                 'columns in subplot specifications must be '
                                 'multiples of one another.')
            return {}

        rowNum1, colNum1 = divmod(num1, cols)
        if num2 is None:
            rowNum2, colNum2 = rowNum1, colNum1
        else:
            rowNum2, colNum2 = divmod(num2, cols)

        num1num2_list.append((rowNum1 * div_row * max_ncols +
                              colNum1 * div_col,
                              ((rowNum2 + 1) * div_row - 1) * max_ncols +
                              (colNum2 + 1) * div_col - 1))

    kwargs = auto_adjust_subplotpars(fig, renderer,
                                     nrows_ncols=(max_nrows, max_ncols),
                                     num1num2_list=num1num2_list,
                                     subplot_list=subplot_list,
                                     ax_bbox_list=ax_bbox_list,
                                     pad=pad, h_pad=h_pad, w_pad=w_pad)

    # kwargs can be none if tight_layout fails...
    if rect is not None and kwargs is not None:
#.........这里部分代码省略.........
开发者ID:QuLogic,项目名称:matplotlib,代码行数:101,代码来源:tight_layout.py


示例18: specgram

def specgram(x, NFFT=None, Fs=None, detrend=None, window=None,
             noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
             mode=None):
    """
    Compute a spectrogram.

    Compute and plot a spectrogram of data in x.  Data are split into
    NFFT length segments and the spectrum of each section is
    computed.  The windowing function window is applied to each
    segment, and the amount of overlap of each segment is
    specified with noverlap.

    Parameters
    ----------
    x : array_like
        1-D array or sequence.

    %(Spectral)s

    %(PSD)s

    noverlap : int, optional
        The number of points of overlap between blocks.  The default
        value is 128.
    mode : str, optional
        What sort of spectrum to use, default is 'psd'.
            'psd'
                Returns the power spectral density.

            'complex'
                Returns the complex-valued frequency spectrum.

            'magnitude'
                Returns the magnitude spectrum.

            'angle'
                Returns the phase spectrum without unwrapping.

            'phase'
                Returns the phase spectrum with unwrapping.

    Returns
    -------
    spectrum : array_like
        2-D array, columns are the periodograms of successive segments.

    freqs : array_like
        1-D array, frequencies corresponding to the rows in *spectrum*.

    t : array_like
        1-D array, the times corresponding to midpoints of segments
        (i.e the columns in *spectrum*).

    See Also
    --------
    psd : differs in the overlap and in the return values.
    complex_spectrum : similar, but with complex valued frequencies.
    magnitude_spectrum : similar single segment when mode is 'magnitude'.
    angle_spectrum : similar to single segment when mode is 'angle'.
    phase_spectrum : similar to single segment when mode is 'phase'.

    Notes
    -----
    detrend and scale_by_freq only apply when *mode* is set to 'psd'.

    """
    if noverlap is None:
        noverlap = 128  # default in _spectral_helper() is noverlap = 0
    if NFFT is None:
        NFFT = 256  # same default as in _spectral_helper()
    if len(x) <= NFFT:
        cbook._warn_external("Only one segment is calculated since parameter "
                             "NFFT (=%d) >= signal length (=%d)." %
                             (NFFT, len(x)))

    spec, freqs, t = _spectral_helper(x=x, y=None, NFFT=NFFT, Fs=Fs,
                                      detrend_func=detrend, window=window,
                                      noverlap=noverlap, pad_to=pad_to,
                                      sides=sides,
                                      scale_by_freq=scale_by_freq,
                                      mode=mode)

    if mode != 'complex':
        spec = spec.real  # Needed since helper implements generically

    return spec, freqs, t
开发者ID:QuLogic,项目名称:matplotlib,代码行数:86,代码来源:mlab.py


示例19: set_aspect

 def set_aspect(self, *args, **kwargs):
     """
     Secondary axes cannot set the aspect ratio, so calling this just
     sets a warning.
     """
     cbook._warn_external("Secondary axes can't set the aspect ratio")
开发者ID:anntzer,项目名称:matplotlib,代码行数:6,代码来源:_secondary_axes.py


示例20: auto_adjust_subplotpars


#.........这里部分代码省略.........

        row1, col1 = divmod(num1, cols)

        if num2 is None:
            # left
            hspaces[row1 * (cols + 1) + col1].append(
                                        _get_left(tight_bbox, ax_bbox))
            # right
            hspaces[row1 * (cols + 1) + (col1 + 1)].append(
                                        _get_right(tight_bbox, ax_bbox))
            # top
            vspaces[row1 * cols + col1].append(
                                        _get_top(tight_bbox, ax_bbox))
            # bottom
            vspaces[(row1 + 1) * cols + col1].append(
                                        _get_bottom(tight_bbox, ax_bbox))

        else:
            row2, col2 = divmod(num2, cols)

            for row_i in range(row1, row2 + 1):
                # left
                hspaces[row_i * (cols + 1) + col1].append(
                                    _get_left(tight_bbox, ax_bbox))
                # right
                hspaces[row_i * (cols + 1) + (col2 + 1)].append(
                                    _get_right(tight_bbox, ax_bbox))
            for col_i in range(col1, col2 + 1):
                # top
                vspaces[row1 * cols + col_i].append(
                                    _get_top(tight_bbox, ax_bbox))
                # bottom
                vspaces[(row2 + 1) * cols + col_i].append(
                                    _get_bottom(tight_bbox, ax_bbox))

    fig_width_inch, fig_height_inch = fig.get_size_inches()

    # margins can be negative for axes with aspect applied. And we
    # append + [0] to make minimum margins 0

    if not margin_left:
        margin_left = max([sum(s) for s in hspaces[::cols + 1]] + [0])
        margin_left += pad_inches / fig_width_inch

    if not margin_right:
        margin_right = max([sum(s) for s in hspaces[cols::cols + 1]] + [0])
        margin_right += pad_inches / fig_width_inch

    if not margin_top:
        margin_top = max([sum(s) for s in vspaces[:cols]] + [0])
        margin_top += pad_inches / fig_height_inch

    if not margin_bottom:
        margin_bottom = max([sum(s) for s in vspaces[-cols:]] + [0])
        margin_bottom += pad_inches / fig_height_inch

    if margin_left + margin_right >= 1:
        cbook._warn_external('Tight layout not applied. The left and right '
                             'margins cannot be made large enough to '
                             'accommodate all axes decorations. ')
        return None
    if margin_bottom + margin_top >= 1:
        cbook._warn_external('Tight layout not applied. The bottom and top '
                             'margins cannot be made large enough to '
                             'accommodate all axes decorations. ')
        return None

    kwargs = dict(left=margin_left,
                  right=1 - margin_right,
                  bottom=margin_bottom,
                  top=1 - margin_top)
    if cols > 1:
        hspace = (
            max(sum(s)
                for i in range(rows)
                for s in hspaces[i * (cols + 1) + 1:(i + 1) * (cols + 1) - 1])
            + hpad_inches / fig_width_inch)
        # axes widths:
        h_axes = (1 - margin_right - margin_left - hspace * (cols - 1)) / cols
        if h_axes < 0:
            cbook._warn_external('Tight layout not applied. tight_layout '
                                 'cannot make axes width small enough to '
                                 'accommodate all axes decorations')
            return None
        else:
            kwargs["wspace"] = hspace / h_axes

    if rows > 1:
        vspace = (max(sum(s) for s in vspaces[cols:-cols])
                  + vpad_inches / fig_height_inch)
        v_axes = (1 - margin_top - margin_bottom - vspace * (rows - 1)) / rows
        if v_axes < 0:
            cbook._warn_external('Tight layout not applied. tight_layout '
                                 'cannot make axes height small enough to '
                                 'accommodate all axes decorations')
            return None
        else:
            kwargs["hspace"] = vspace / v_axes

    return kwargs
开发者ID:QuLogic,项目名称:matplotlib,代码行数:101,代码来源:tight_layout.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python cbook.boxplot_stats函数代码示例发布时间:2022-05-27
下一篇:
Python cbook._setattr_cm函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap