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*. rect : tuple of 4 floats, default: (0, 0, 1, 1), i.e. the whole figure (left, bottom, right, top) rectangle in normalized figure coordinates that the whole subplots area (including labels) will fit into. """ subplotspec_list = tight_layout.get_subplotspec_list( figure.axes, grid_spec=self) if None in subplotspec_list: _api.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)
def get_tool(self, name, warn=True): """ Return the tool object with the given name. For convenience, this passes tool objects through. Parameters ---------- name : str or `.ToolBase` Name of the tool, or the tool itself. warn : bool, default: True Whether a warning should be emitted it no tool with the given name exists. Returns ------- `.ToolBase` or None The tool or None if no tool with the given name exists. """ if isinstance(name, tools.ToolBase) and name.name in self._tools: return name if name not in self._tools: if warn: _api.warn_external(f"ToolManager does not control tool {name}") return None return self._tools[name]
def new_fixed_axis( self, loc, nth_coord=None, axis_direction=None, offset=None, axes=None, ): if axes is None: _api.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
def _get_legend_handles(axs, legend_handler_map=None): """Yield artists that can be used as handles in a legend.""" handles_original = [] for ax in axs: handles_original += [ *(a for a in ax._children if isinstance(a, (Line2D, Patch, Collection, Text))), *ax.containers] # support parasite axes: if hasattr(ax, 'parasites'): for axx in ax.parasites: handles_original += [ *(a for a in axx._children if isinstance(a, (Line2D, Patch, Collection, Text))), *axx.containers] handler_map = {**Legend.get_default_handler_map(), **(legend_handler_map or {})} has_handler = Legend.get_legend_handler for handle in handles_original: label = handle.get_label() if label != '_nolegend_' and has_handler(handler_map, handle): yield handle elif (label not in ['_nolegend_', ''] and not has_handler(handler_map, handle)): _api.warn_external( "Legend does not support handles for {0} " "instances.\nSee: https://matplotlib.org/stable/" "tutorials/intermediate/legend_guide.html" "#implementing-a-custom-legend-handler".format( type(handle).__name__)) continue
def get_from_args_and_kwargs(*args, **kwargs): """ Return a Triangulation object from the args and kwargs, and the remaining args and kwargs with the consumed values removed. There are two alternatives: either the first argument is a Triangulation object, in which case it is returned, or the args and kwargs are sufficient to create a new Triangulation to return. In the latter case, see Triangulation.__init__ for the possible args and kwargs. """ if isinstance(args[0], Triangulation): triangulation, *args = args if 'triangles' in kwargs: _api.warn_external( "Passing the keyword 'triangles' has no effect when also " "passing a Triangulation") if 'mask' in kwargs: _api.warn_external( "Passing the keyword 'mask' has no effect when also " "passing a Triangulation") else: x, y, triangles, mask, args, kwargs = \ Triangulation._extract_triangulation_params(args, kwargs) triangulation = Triangulation(x, y, triangles, mask) return triangulation, args, kwargs
def __init__(self, toolmanager, name): _api.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
def execute(self, fig): """ Execute tight_layout. This decides the subplot parameters given the padding that will allow the axes labels to not be covered by other labels and axes. Parameters ---------- fig : `.Figure` to perform layout on. See also: `.figure.Figure.tight_layout` and `.pyplot.tight_layout`. """ info = self._params subplotspec_list = get_subplotspec_list(fig.axes) if None in subplotspec_list: _api.warn_external("This figure includes Axes that are not " "compatible with tight_layout, so results " "might be incorrect.") renderer = _get_renderer(fig) with getattr(renderer, "_draw_disabled", nullcontext)(): kwargs = get_tight_layout_figure(fig, fig.axes, subplotspec_list, renderer, pad=info['pad'], h_pad=info['h_pad'], w_pad=info['w_pad'], rect=info['rect']) if kwargs: fig.subplots_adjust(**kwargs)
def update_keymap(self, name, key, *args): """ Set the keymap to associate with the specified tool. Parameters ---------- name : str Name of the Tool. key : str or list of str 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 [key, *args]: if isinstance(key, str) and validate_stringlist(key) != [key]: _api.warn_deprecated( "3.3", message="Passing a list of keys as a single " "comma-separated string is deprecated since %(since)s and " "support will be removed %(removal)s; pass keys as a list " "of strings instead.") key = validate_stringlist(key) if isinstance(key, str): key = [key] for k in key: if k in self._keys: _api.warn_external( f'Key {k} changed from {self._keys[k]} to {name}') self._keys[k] = name
def _validate_toolbar(s): s = ValidateInStrings('toolbar', ['None', 'toolbar2', 'toolmanager'], ignorecase=True)(s) if s == 'toolmanager': _api.warn_external( "Treat the new Tool classes introduced in v1.5 as experimental " "for now; the API and rcParam may change in future versions.") return s
def _create_qApp(): """ Only one qApp can exist at a time, so check before creating one. """ global qApp if qApp is None: app = QtWidgets.QApplication.instance() if app is None: # display_is_valid returns False only if on Linux and neither X11 # nor Wayland display can be opened. if not mpl._c_internal_utils.display_is_valid(): raise RuntimeError('Invalid DISPLAY variable') try: QtWidgets.QApplication.setAttribute( QtCore.Qt.AA_EnableHighDpiScaling) except AttributeError: # Only for Qt>=5.6, <6. pass # Check to make sure a QApplication from a different major version # of Qt is not instantiated in the process if QT_API in {'PyQt6', 'PySide6'}: other_bindings = ('PyQt5', 'PySide2') elif QT_API in {'PyQt5', 'PySide2'}: other_bindings = ('PyQt6', 'PySide6') else: raise RuntimeError("Should never be here") for binding in other_bindings: mod = sys.modules.get(f'{binding}.QtWidgets') if mod is not None and mod.QApplication.instance() is not None: other_core = sys.modules.get(f'{binding}.QtCore') _api.warn_external( f'Matplotlib is using {QT_API} which wraps ' f'{QtCore.qVersion()} however an instantiated ' f'QApplication from {binding} which wraps ' f'{other_core.qVersion()} exists. Mixing Qt major ' 'versions may not work as expected.') break try: QtWidgets.QApplication.setHighDpiScaleFactorRoundingPolicy( QtCore.Qt.HighDpiScaleFactorRoundingPolicy.PassThrough) except AttributeError: # Only for Qt>=5.14. pass qApp = QtWidgets.QApplication(["matplotlib"]) if sys.platform == "darwin": image = str(cbook._get_data_path('images/matplotlib.svg')) icon = QtGui.QIcon(image) qApp.setWindowIcon(icon) qApp.lastWindowClosed.connect(qApp.quit) cbook._setup_new_guiapp() else: qApp = app try: qApp.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps) # Only for Qt<6. except AttributeError: pass
def register_cmap(name=None, cmap=None, *, override_builtin=False): """ Add a colormap to the set recognized by :func:`get_cmap`. Register a new colormap to be accessed by name :: LinearSegmentedColormap('swirly', data, lut) register_cmap(cmap=swirly_cmap) Parameters ---------- name : str, optional The name that can be used in :func:`get_cmap` or :rc:`image.cmap` If absent, the name will be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*. cmap : matplotlib.colors.Colormap Despite being the second argument and having a default value, this is a required argument. override_builtin : bool Allow built-in colormaps to be overridden by a user-supplied colormap. Please do not use this unless you are sure you need it. Notes ----- Registering a colormap stores a reference to the colormap object which can currently be modified and inadvertently change the global colormap state. This behavior is deprecated and in Matplotlib 3.5 the registered colormap will be immutable. """ _api.check_isinstance((str, None), name=name) if name is None: try: name = cmap.name except AttributeError as err: raise ValueError("Arguments must include a name or a " "Colormap") from err if name in _cmap_registry: if not override_builtin and name in __builtin_cmaps: msg = f"Trying to re-register the builtin cmap {name!r}." raise ValueError(msg) else: msg = f"Trying to register the cmap {name!r} which already exists." _api.warn_external(msg) if not isinstance(cmap, colors.Colormap): raise ValueError("You must pass a Colormap instance. " f"You passed {cmap} a {type(cmap)} object.") cmap._global = True _cmap_registry[name] = cmap return
def to_qcolor(color): """Create a QColor from a matplotlib color""" qcolor = QtGui.QColor() try: rgba = mcolors.to_rgba(color) except ValueError: _api.warn_external(f'Ignoring invalid color {color!r}') return qcolor # return invalid QColor qcolor.setRgbF(*rgba) return qcolor
def _validate_date_converter(s): if s is None: return s = validate_string(s) if s not in ['auto', 'concise']: _api.warn_external(f'date.converter string must be "auto" or ' f'"concise", not "{s}". Check your matplotlibrc') return import matplotlib.dates as mdates mdates._rcParam_helper.set_converter(s)
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 every time 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: _api.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
def latex2png(latex, filename, fontset='cm', fontsize=10, dpi=100): with mpl.rc_context({'mathtext.fontset': fontset, 'font.size': fontsize}): try: depth = mathtext.math_to_image(f"${latex}$", filename, dpi=dpi, format="png") except Exception: _api.warn_external(f"Could not render math expression {latex}") depth = 0 return depth
def _remove_blacklisted_style_params(d, warn=True): o = {} for key in d: # prevent triggering RcParams.__getitem__('backend') if key in STYLE_BLACKLIST: if warn: _api.warn_external( "Style includes a parameter, '{0}', that is not related " "to style. Ignoring".format(key)) else: o[key] = d[key] return o
def _remove_blacklisted_style_params(d, warn=True): o = {} for key in d: # prevent triggering RcParams.__getitem__('backend') if key in STYLE_BLACKLIST: if warn: _api.warn_external( f"Style includes a parameter, {key!r}, that is not " "related to style. Ignoring this parameter.") else: o[key] = d[key] return o
def latex2png(latex, filename, fontset='cm'): latex = "$%s$" % latex with mpl.rc_context({'mathtext.fontset': fontset}): try: depth = mathtext.math_to_image(latex, filename, dpi=100, format="png") except Exception: _api.warn_external(f"Could not render math expression {latex}") depth = 0 return depth
def show(self): # show the figure window self.window.show() self.canvas.draw() if mpl.rcParams['figure.raise_window']: if self.window.get_window(): self.window.present() else: # If this is called by a callback early during init, # self.window (a GtkWindow) may not have an associated # low-level GdkWindow (self.window.get_window()) yet, and # present() would crash. _api.warn_external("Cannot raise window yet to be setup")
def show(self): # show the figure window self.window.show() self.canvas.draw() if mpl.rcParams["figure.raise_window"]: meth_name = {3: "get_window", 4: "get_surface"}[self._gtk_ver] if getattr(self.window, meth_name)(): self.window.present() else: # If this is called by a callback early during init, # self.window (a GtkWindow) may not have an associated # low-level GdkWindow (on GTK3) or GdkSurface (on GTK4) yet, # and present() would crash. _api.warn_external("Cannot raise window yet to be setup")
def register(self, cmap, *, name=None, force=False): """ Register a new colormap. The colormap name can then be used as a string argument to any ``cmap`` parameter in Matplotlib. It is also available in ``pyplot.get_cmap``. The colormap registry stores a copy of the given colormap, so that future changes to the original colormap instance do not affect the registered colormap. Think of this as the registry taking a snapshot of the colormap at registration. Parameters ---------- cmap : matplotlib.colors.Colormap The colormap to register. name : str, optional The name for the colormap. If not given, ``cmap.name`` is used. force : bool, default: False If False, a ValueError is raised if trying to overwrite an already registered name. True supports overwriting registered colormaps other than the builtin colormaps. """ _api.check_isinstance(colors.Colormap, cmap=cmap) name = name or cmap.name if name in self: if not force: # don't allow registering an already existing cmap # unless explicitly asked to raise ValueError( f'A colormap named "{name}" is already registered.') elif (name in self._builtin_cmaps and not self._allow_override_builtin): # We don't allow overriding a builtin unless privately # coming from register_cmap() raise ValueError("Re-registering the builtin cmap " f"{name!r} is not allowed.") # Warn that we are updating an already existing colormap _api.warn_external(f"Overwriting the cmap {name!r} " "that was already in the registry.") self._cmaps[name] = cmap.copy()
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. """ assert self.isaxes # always holds, as this is only called internally start_time = time.perf_counter() bboxes, lines, offsets = self._auto_legend_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 = ( sum(legendBox.count_contains(line.vertices) for line in lines) + 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) if self._loc_used_default and time.perf_counter() - start_time > 1: _api.warn_external( 'Creating legend with loc="best" can be slow with large ' 'amounts of data.') return l, b
def new_floating_axis(self, nth_coord, value, axis_direction="bottom", axes=None, ): if axes is None: _api.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
def update_keymap(self, name, key): """ Set the keymap to associate with the specified tool. Parameters ---------- name : str Name of the Tool. key : str or list of str Keys to associate with the tool. """ if name not in self._tools: raise KeyError(f'{name} not in Tools') self._remove_keys(name) if isinstance(key, str): key = [key] for k in key: if k in self._keys: _api.warn_external( f'Key {k} changed from {self._keys[k]} to {name}') self._keys[k] = name
def draw_image(self, gc, x, y, im, transform=None): # docstring inherited h, w = im.shape[:2] if w == 0 or h == 0: return if not os.path.exists(getattr(self.fh, "name", "")): _api.warn_external( "streamed pgf-code does not support raster graphics, consider " "using the pgf-to-pdf option.") # save the images to png files path = pathlib.Path(self.fh.name) fname_img = "%s-img%d.png" % (path.stem, self.image_counter) Image.fromarray(im[::-1]).save(path.parent / fname_img) self.image_counter += 1 # reference the image in the pgf picture writeln(self.fh, r"\begin{pgfscope}") self._print_pgf_clip(gc) f = 1. / self.dpi # from display coords to inch if transform is None: writeln(self.fh, r"\pgfsys@transformshift{%fin}{%fin}" % (x * f, y * f)) w, h = w * f, h * f else: tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values() writeln(self.fh, r"\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}" % (tr1 * f, tr2 * f, tr3 * f, tr4 * f, (tr5 + x) * f, (tr6 + y) * f)) w = h = 1 # scale is already included in the transform interp = str(transform is None).lower() # interpolation in PDF reader writeln(self.fh, r"\pgftext[left,bottom]" r"{%s[interpolate=%s,width=%fin,height=%fin]{%s}}" % (_get_image_inclusion_command(), interp, w, h, fname_img)) writeln(self.fh, r"\end{pgfscope}")
def inset_axes(parent_axes, width, height, loc='upper right', bbox_to_anchor=None, bbox_transform=None, axes_class=None, axes_kwargs=None, borderpad=0.5): """ Create an inset axes with a given width and height. Both sizes used can be specified either in inches or percentage. For example,:: inset_axes(parent_axes, width='40%%', height='30%%', loc='lower left') creates in inset axes in the lower left corner of *parent_axes* which spans over 30%% in height and 40%% in width of the *parent_axes*. Since the usage of `.inset_axes` may become slightly tricky when exceeding such standard cases, it is recommended to read :doc:`the examples </gallery/axes_grid1/inset_locator_demo>`. Notes ----- The meaning of *bbox_to_anchor* and *bbox_to_transform* is interpreted differently from that of legend. The value of bbox_to_anchor (or the return value of its get_points method; the default is *parent_axes.bbox*) is transformed by the bbox_transform (the default is Identity transform) and then interpreted as points in the pixel coordinate (which is dpi dependent). Thus, following three calls are identical and creates an inset axes with respect to the *parent_axes*:: axins = inset_axes(parent_axes, "30%%", "40%%") axins = inset_axes(parent_axes, "30%%", "40%%", bbox_to_anchor=parent_axes.bbox) axins = inset_axes(parent_axes, "30%%", "40%%", bbox_to_anchor=(0, 0, 1, 1), bbox_transform=parent_axes.transAxes) Parameters ---------- parent_axes : `matplotlib.axes.Axes` Axes to place the inset axes. width, height : float or str Size of the inset axes to create. If a float is provided, it is the size in inches, e.g. *width=1.3*. If a string is provided, it is the size in relative units, e.g. *width='40%%'*. By default, i.e. if 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 : str, default: 'upper right' Location to place the inset axes. Valid locations are 'upper left', 'upper center', 'upper right', 'center left', 'center', 'center right', 'lower left', 'lower center, 'lower right'. For backward compatibility, numeric values are accepted as well. See the parameter *loc* of `.Legend` for details. 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, default: `.HostAxes` The type of the newly created inset axes. axes_kwargs : dict, optional Keyword arguments to pass to the constructor of the inset axes. Valid arguments include: %(Axes:kwdoc)s borderpad : float, default: 0.5 Padding between inset axes and the bbox_to_anchor. 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: axes_kwargs = {} 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: _api.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
def _auto_adjust_subplotpars( fig, renderer, shape, span_pairs, subplot_list, ax_bbox_list=None, pad=1.08, h_pad=None, w_pad=None, rect=None): """ Return a dict of subplot parameters to adjust spacing between subplots or ``None`` if resulting axes would have zero height or width. Note that this function ignores geometry information of subplot itself, but uses what is given by the *shape* and *subplot_list* parameters. Also, the results could be incorrect if some subplots have ``adjustable=datalim``. Parameters ---------- shape : tuple[int, int] Number of rows and columns of the grid. span_pairs : list[tuple[slice, slice]] List of rowspans and colspans occupied by each subplot. subplot_list : list of subplots List of subplots that will be used to calculate optimal subplot_params. 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, as a fraction of the font size. Defaults to *pad*. rect : tuple[float, float, float, float] [left, bottom, right, top] in normalized (0, 1) figure coordinates. """ rows, cols = shape font_size_inch = ( FontProperties(size=rcParams["font.size"]).get_size_in_points() / 72) pad_inch = pad * font_size_inch vpad_inch = h_pad * font_size_inch if h_pad is not None else pad_inch hpad_inch = w_pad * font_size_inch if w_pad is not None else pad_inch if len(span_pairs) != len(subplot_list) or len(subplot_list) == 0: raise ValueError if rect is None: margin_left = margin_bottom = margin_right = margin_top = None else: margin_left, margin_bottom, _right, _top = rect margin_right = 1 - _right if _right else None margin_top = 1 - _top if _top else None vspaces = np.zeros((rows + 1, cols)) hspaces = np.zeros((rows, cols + 1)) if ax_bbox_list is None: ax_bbox_list = [ Bbox.union([ax.get_position(original=True) for ax in subplots]) for subplots in subplot_list] for subplots, ax_bbox, (rowspan, colspan) in zip( subplot_list, ax_bbox_list, span_pairs): if all(not ax.get_visible() for ax in subplots): continue bb = [] for ax in subplots: if ax.get_visible(): bb += [martist._get_tightbbox_for_layout_only(ax, renderer)] tight_bbox_raw = Bbox.union(bb) tight_bbox = fig.transFigure.inverted().transform_bbox(tight_bbox_raw) hspaces[rowspan, colspan.start] += ax_bbox.xmin - tight_bbox.xmin # l hspaces[rowspan, colspan.stop] += tight_bbox.xmax - ax_bbox.xmax # r vspaces[rowspan.start, colspan] += tight_bbox.ymax - ax_bbox.ymax # t vspaces[rowspan.stop, colspan] += ax_bbox.ymin - tight_bbox.ymin # b fig_width_inch, fig_height_inch = fig.get_size_inches() # margins can be negative for axes with aspect applied, so use max(, 0) to # make them nonnegative. if not margin_left: margin_left = max(hspaces[:, 0].max(), 0) + pad_inch/fig_width_inch suplabel = fig._supylabel if suplabel and suplabel.get_in_layout(): rel_width = fig.transFigure.inverted().transform_bbox( suplabel.get_window_extent(renderer)).width margin_left += rel_width + pad_inch/fig_width_inch if not margin_right: margin_right = max(hspaces[:, -1].max(), 0) + pad_inch/fig_width_inch if not margin_top: margin_top = max(vspaces[0, :].max(), 0) + pad_inch/fig_height_inch if fig._suptitle and fig._suptitle.get_in_layout(): rel_height = fig.transFigure.inverted().transform_bbox( fig._suptitle.get_window_extent(renderer)).height margin_top += rel_height + pad_inch/fig_height_inch if not margin_bottom: margin_bottom = max(vspaces[-1, :].max(), 0) + pad_inch/fig_height_inch suplabel = fig._supxlabel if suplabel and suplabel.get_in_layout(): rel_height = fig.transFigure.inverted().transform_bbox( suplabel.get_window_extent(renderer)).height margin_bottom += rel_height + pad_inch/fig_height_inch if margin_left + margin_right >= 1: _api.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: _api.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 = hspaces[:, 1:-1].max() + hpad_inch / fig_width_inch # axes widths: h_axes = (1 - margin_right - margin_left - hspace * (cols - 1)) / cols if h_axes < 0: _api.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 = vspaces[1:-1, :].max() + vpad_inch / fig_height_inch v_axes = (1 - margin_top - margin_bottom - vspace * (rows - 1)) / rows if v_axes < 0: _api.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
def get_parallels(bezier2, width): """ Given the quadratic Bezier control points *bezier2*, returns control points of quadratic Bezier lines roughly parallel to given one separated by *width*. """ # The parallel Bezier lines are constructed by following ways. # c1 and c2 are control points representing the begin and end of the # Bezier line. # cm is the middle point c1x, c1y = bezier2[0] cmx, cmy = bezier2[1] c2x, c2y = bezier2[2] parallel_test = check_if_parallel(c1x - cmx, c1y - cmy, cmx - c2x, cmy - c2y) if parallel_test == -1: _api.warn_external( "Lines do not intersect. A straight line is used instead.") cos_t1, sin_t1 = get_cos_sin(c1x, c1y, c2x, c2y) cos_t2, sin_t2 = cos_t1, sin_t1 else: # t1 and t2 is the angle between c1 and cm, cm, c2. They are # also a angle of the tangential line of the path at c1 and c2 cos_t1, sin_t1 = get_cos_sin(c1x, c1y, cmx, cmy) cos_t2, sin_t2 = get_cos_sin(cmx, cmy, c2x, c2y) # find c1_left, c1_right which are located along the lines # through c1 and perpendicular to the tangential lines of the # Bezier path at a distance of width. Same thing for c2_left and # c2_right with respect to c2. c1x_left, c1y_left, c1x_right, c1y_right = ( get_normal_points(c1x, c1y, cos_t1, sin_t1, width) ) c2x_left, c2y_left, c2x_right, c2y_right = ( get_normal_points(c2x, c2y, cos_t2, sin_t2, width) ) # find cm_left which is the intersecting point of a line through # c1_left with angle t1 and a line through c2_left with angle # t2. Same with cm_right. try: cmx_left, cmy_left = get_intersection(c1x_left, c1y_left, cos_t1, sin_t1, c2x_left, c2y_left, cos_t2, sin_t2) cmx_right, cmy_right = get_intersection(c1x_right, c1y_right, cos_t1, sin_t1, c2x_right, c2y_right, cos_t2, sin_t2) except ValueError: # Special case straight lines, i.e., angle between two lines is # less than the threshold used by get_intersection (we don't use # check_if_parallel as the threshold is not the same). cmx_left, cmy_left = ( 0.5 * (c1x_left + c2x_left), 0.5 * (c1y_left + c2y_left) ) cmx_right, cmy_right = ( 0.5 * (c1x_right + c2x_right), 0.5 * (c1y_right + c2y_right) ) # the parallel Bezier lines are created with control points of # [c1_left, cm_left, c2_left] and [c1_right, cm_right, c2_right] path_left = [(c1x_left, c1y_left), (cmx_left, cmy_left), (c2x_left, c2y_left)] path_right = [(c1x_right, c1y_right), (cmx_right, cmy_right), (c2x_right, c2y_right)] return path_left, path_right
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*. 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. """ # Multiple axes can share same subplotspec (e.g., if using axes_grid1); # we need to group them together. ss_to_subplots = {ss: [] for ss in subplotspec_list} for ax, ss in zip(axes_list, subplotspec_list): ss_to_subplots[ss].append(ax) ss_to_subplots.pop(None, None) # Skip subplotspec == None. if not ss_to_subplots: return {} subplot_list = list(ss_to_subplots.values()) ax_bbox_list = [ss.get_position(fig) for ss in ss_to_subplots] max_nrows = max(ss.get_gridspec().nrows for ss in ss_to_subplots) max_ncols = max(ss.get_gridspec().ncols for ss in ss_to_subplots) span_pairs = [] for ss in ss_to_subplots: # The intent here is to support axes from different gridspecs where # one's nrows (or ncols) is a multiple of the other (e.g. 2 and 4), # but this doesn't actually work because the computed wspace, in # relative-axes-height, corresponds to different physical spacings for # the 2-row grid and the 4-row grid. Still, this code is left, mostly # for backcompat. rows, cols = ss.get_gridspec().get_geometry() div_row, mod_row = divmod(max_nrows, rows) div_col, mod_col = divmod(max_ncols, cols) if mod_row != 0: _api.warn_external('tight_layout not applied: number of rows ' 'in subplot specifications must be ' 'multiples of one another.') return {} if mod_col != 0: _api.warn_external('tight_layout not applied: number of ' 'columns in subplot specifications must be ' 'multiples of one another.') return {} span_pairs.append(( slice(ss.rowspan.start * div_row, ss.rowspan.stop * div_row), slice(ss.colspan.start * div_col, ss.colspan.stop * div_col))) kwargs = _auto_adjust_subplotpars(fig, renderer, shape=(max_nrows, max_ncols), span_pairs=span_pairs, 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: # if rect is given, the whole subplots area (including # labels) will fit into the rect instead of the # figure. Note that the rect argument of # *auto_adjust_subplotpars* specify the area that will be # covered by the total area of axes.bbox. Thus we call # auto_adjust_subplotpars twice, where the second run # with adjusted rect parameters. left, bottom, right, top = rect if left is not None: left += kwargs["left"] if bottom is not None: bottom += kwargs["bottom"] if right is not None: right -= (1 - kwargs["right"]) if top is not None: top -= (1 - kwargs["top"]) kwargs = _auto_adjust_subplotpars(fig, renderer, shape=(max_nrows, max_ncols), span_pairs=span_pairs, subplot_list=subplot_list, ax_bbox_list=ax_bbox_list, pad=pad, h_pad=h_pad, w_pad=w_pad, rect=(left, bottom, right, top)) return kwargs
def subplots(self, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None): """ Add all subplots specified by this `GridSpec` to its parent figure. See `.Figure.subplots` for detailed documentation. """ figure = self.figure if figure is None: raise ValueError("GridSpec.subplots() only works for GridSpecs " "created with a parent figure") if isinstance(sharex, bool): sharex = "all" if sharex else "none" if isinstance(sharey, bool): sharey = "all" if sharey else "none" # This check was added because it is very easy to type # `subplots(1, 2, 1)` when `subplot(1, 2, 1)` was intended. # In most cases, no error will ever occur, but mysterious behavior # will result because what was intended to be the subplot index is # instead treated as a bool for sharex. This check should go away # once sharex becomes kwonly. if isinstance(sharex, Integral): _api.warn_external( "sharex argument to subplots() was an integer. Did you " "intend to use subplot() (without 's')?") _api.check_in_list(["all", "row", "col", "none"], sharex=sharex, sharey=sharey) if subplot_kw is None: subplot_kw = {} # don't mutate kwargs passed by user... subplot_kw = subplot_kw.copy() # Create array to hold all axes. axarr = np.empty((self._nrows, self._ncols), dtype=object) for row in range(self._nrows): for col in range(self._ncols): shared_with = { "none": None, "all": axarr[0, 0], "row": axarr[row, 0], "col": axarr[0, col] } subplot_kw["sharex"] = shared_with[sharex] subplot_kw["sharey"] = shared_with[sharey] axarr[row, col] = figure.add_subplot(self[row, col], **subplot_kw) # turn off redundant tick labeling if sharex in ["col", "all"]: for ax in axarr.flat: ax._label_outer_xaxis(check_patch=True) if sharey in ["row", "all"]: for ax in axarr.flat: ax._label_outer_yaxis(check_patch=True) if squeeze: # Discarding unneeded dimensions that equal 1. If we only have one # subplot, just return it instead of a 1-element array. return axarr.item() if axarr.size == 1 else axarr.squeeze() else: # Returned axis array will be always 2-d, even if nrows=ncols=1. return axarr