_OrderedSet, _check_1d, _string_to_bool, iterable, index_of, get_label)
""" Process a MATLAB style color/line style format string. Return a (*linestyle*, *color*) tuple as a result of the processing. Default values are ('-', 'b'). Example format strings include:
* 'ko': black circles * '.b': blue dots * 'r--': red dashed lines * 'C2--': the third color in the color cycle, dashed lines
.. seealso::
:func:`~matplotlib.Line2D.lineStyles` and :attr:`~matplotlib.colors.cnames` for all possible styles and color format string. """
# Is fmt just a colorspec?
# We need to differentiate grayscale '1.0' from tri_down marker '1' else: if fmt != fmtint: # user definitely doesn't want tri_down marker return linestyle, marker, color # Yes else: # ignore converted color color = None
# handle the multi char special cases and strip them from the # string linestyle = '--' fmt = fmt.replace('--', '') linestyle = '-.' fmt = fmt.replace('-.', '') linestyle = 'None' fmt = fmt.replace(' ', '')
if linestyle is not None: raise ValueError( 'Illegal format string "%s"; two linestyle symbols' % fmt) linestyle = c raise ValueError( 'Illegal format string "%s"; two marker symbols' % fmt) elif c in mcolors.get_named_colors_mapping(): if color is not None: raise ValueError( 'Illegal format string "%s"; two color symbols' % fmt) color = c elif c == 'C' and i < len(chars) - 1: color_cycle_number = int(chars[i + 1]) color = mcolors.to_rgba("C{}".format(color_cycle_number)) i += 1 else: raise ValueError( 'Unrecognized character %c in format string' % c)
linestyle = rcParams['lines.linestyle'] marker = 'None'
""" Process variable length arguments to the plot command, so that plot commands like the following are supported::
plot(t, s) plot(t1, s1, t2, s2) plot(t1, s1, 'ko', t2, s2) plot(t1, s1, 'ko', t2, s2, 'r--', t3, e3)
an arbitrary number of *x*, *y*, *fmt* are allowed """
# note: it is not possible to pickle a generator (and thus a cycler). return {'axes': self.axes, 'command': self.command}
self.__dict__ = state.copy() self.set_prop_cycle()
# Can't do `args == (None,)` as that crashes cycler. else: prop_cycler = cycler(*args, **kwargs)
# This should make a copy
xunits = kwargs.pop('thetaunits', xunits)
yunits = kwargs.pop('runits', yunits)
self.axes.xaxis.set_units(xunits)
self.axes.yaxis.set_units(yunits)
"""Return the next color in the cycle.""" if 'color' not in self._prop_keys: return 'k' return next(self.prop_cycler)['color']
assert self.command == 'plot', 'set_lineprops only works with "plot"' line.set(**kwargs)
# the Line2D class can handle unitized data, with # support for post hoc unit changes etc. Other mpl # artists, e.g., Polygon which _process_plot_var_args # also serves on calls to fill, cannot. So this is a # hack to say: if you are not "plot", which is # creating Line2D, then convert the data now to # floats. If you are plot, pass the raw data through # to Line2D which will handle the conversion. So # polygons will not support post hoc conversions of # the unit type since they are not storing the orig # data. Hopefully we can rationalize this at a later # date - JDH x = self.axes.convert_xunits(x) y = self.axes.convert_yunits(y)
# like asanyarray, but converts scalar to array, and doesn't change # existing compatible sequences raise ValueError("x and y must have same first dimension, but " "have shapes {} and {}".format(x.shape, y.shape)) raise ValueError("x and y can be no greater than 2-D, but have " "shapes {} and {}".format(x.shape, y.shape))
""" Only advance the cycler if the cycler has information that is not specified in any of the supplied tuple of dicts. Ignore any keys specified in the `ignore` set.
Returns a copy of defaults dictionary if there are any keys that are not found in any of the supplied dictionaries. If the supplied dictionaries have non-None values for everything the property cycler has, then just return an empty dictionary. Ignored keys are excluded from the returned dictionary.
"""
for k in prop_keys): # Need to copy this dictionary or else the next time around # in the cycle, the dictionary could be missing entries. else:
""" Given a defaults dictionary, and any other dictionaries, update those other dictionaries with information in defaults if none of the other dictionaries contains that information.
"""
# Ignore 'marker'-related properties as they aren't Polygon # properties, but they are Line2D properties, and so they are # likely to appear in the default cycler construction. # This is done here to the defaults dictionary as opposed to the # other two dictionaries because we do want to capture when a # *user* explicitly specifies a marker which should be an error. # We also want to prevent advancing the cycler if there are no # defaults needed after ignoring the given properties. 'markerfacecolor', 'markeredgewidth'} # Also ignore anything provided by *kwargs*.
# Only using the first dictionary to use as basis # for getting defaults for back-compat reasons. # Doing it with both seems to mess things up in # various places (probably due to logic bugs elsewhere).
# Looks like we don't want "color" to be interpreted to # mean both facecolor and edgecolor for some reason. # So the "kw" dictionary is thrown out, and only its # 'color' value is kept and translated as a 'facecolor'. # This design should probably be revisited as it increases # complexity.
# Throw out 'color' as it is now handled as a facecolor
# To get other properties set from the cycler # modify the kwargs dictionary.
facecolor=facecolor, fill=kwargs.get('fill', True), closed=kw['closed'])
raise ValueError('third arg must be a format string') else:
# Don't allow any None value; These will be up-converted # to one element array of None which causes problems # downstream. raise ValueError("x, y, and format string must not be None")
(linestyle, marker, color)):
else:
else:
cbook.warn_deprecated("2.2", "cycling among columns of inputs " "with non-matching shapes is deprecated.")
""" """
def _hold(self): return True
def _hold(self, value): pass
def __str__(self): return "{0}({1[0]:g},{1[1]:g};{1[2]:g}x{1[3]:g})".format( type(self).__name__, self._position.bounds)
facecolor=None, # defaults to rc axes.facecolor frameon=True, sharex=None, # use Axes instance's xaxis info sharey=None, # use Axes instance's yaxis info label='', xscale=None, yscale=None, **kwargs ): """ Build an axes in a figure.
Parameters ---------- fig : `~matplotlib.figure.Figure` The axes is build in the `.Figure` *fig*.
rect : [left, bottom, width, height] The axes is build in the rectangle *rect*. *rect* is in `.Figure` coordinates.
sharex, sharey : `~.axes.Axes`, optional The x or y `~.matplotlib.axis` is shared with the x or y axis in the input `~.axes.Axes`.
frameon : bool, optional True means that the axes frame is visible.
**kwargs Other optional keyword arguments: %(Axes)s
Returns ------- axes : `~.axes.Axes` The new `~.axes.Axes` object. """
else: raise ValueError('Width and height specified must be non-negative') self._shared_y_axes.join(self, sharey)
# this call may differ for non-sep axes, e.g., polar
# funcs used to format x and y - fall back on major formatters
self.set_xscale(xscale) self.set_yscale(yscale)
'units finalize', lambda: self._on_units_changed(scalex=True))
'units finalize', lambda: self._on_units_changed(scaley=True))
top=rcParams['xtick.top'] and rcParams['xtick.minor.top'], bottom=rcParams['xtick.bottom'] and rcParams['xtick.minor.bottom'], labeltop=(rcParams['xtick.labeltop'] and rcParams['xtick.minor.top']), labelbottom=(rcParams['xtick.labelbottom'] and rcParams['xtick.minor.bottom']), left=rcParams['ytick.left'] and rcParams['ytick.minor.left'], right=rcParams['ytick.right'] and rcParams['ytick.minor.right'], labelleft=(rcParams['ytick.labelleft'] and rcParams['ytick.minor.left']), labelright=(rcParams['ytick.labelright'] and rcParams['ytick.minor.right']), which='minor')
top=rcParams['xtick.top'] and rcParams['xtick.major.top'], bottom=rcParams['xtick.bottom'] and rcParams['xtick.major.bottom'], labeltop=(rcParams['xtick.labeltop'] and rcParams['xtick.major.top']), labelbottom=(rcParams['xtick.labelbottom'] and rcParams['xtick.major.bottom']), left=rcParams['ytick.left'] and rcParams['ytick.major.left'], right=rcParams['ytick.right'] and rcParams['ytick.major.right'], labelleft=(rcParams['ytick.labelleft'] and rcParams['ytick.major.left']), labelright=(rcParams['ytick.labelright'] and rcParams['ytick.major.right']), which='major')
# The renderer should be re-created by the figure, and then cached at # that point. state = super().__getstate__() for key in ['_cachedRenderer', '_layoutbox', '_poslayoutbox']: state[key] = None # Prune the sharing & twinning info to only contain the current group. for grouper_name in [ '_shared_x_axes', '_shared_y_axes', '_twinned_axes']: grouper = getattr(self, grouper_name) state[grouper_name] = (grouper.get_siblings(self) if self in grouper else None) return state
# Merge the grouping info back into the global groupers. for grouper_name in [ '_shared_x_axes', '_shared_y_axes', '_twinned_axes']: siblings = state.pop(grouper_name) if siblings: getattr(self, grouper_name).join(*siblings) self.__dict__ = state self._stale = True
""" get the axes bounding box in display space; *args* and *kwargs* are empty """ bbox = self.bbox x_pad = 0 if self.axison and self.xaxis.get_visible(): x_pad = self.xaxis.get_tick_padding() y_pad = 0 if self.axison and self.yaxis.get_visible(): y_pad = self.yaxis.get_tick_padding() return mtransforms.Bbox([[bbox.x0 - x_pad, bbox.y0 - y_pad], [bbox.x1 + x_pad, bbox.y1 + y_pad]])
"move this out of __init__ because non-separable axes don't use it"
""" Set the `.Figure` for this `.Axes`.
Parameters ---------- fig : `.Figure` """
fig.transFigure) # these will be updated later as data is added mtransforms.IdentityTransform())
""" set the *_xaxis_transform*, *_yaxis_transform*, *transScale*, *transData*, *transLimits* and *transAxes* transformations.
.. note::
This method is primarily used by rectilinear projections of the :class:`~matplotlib.axes.Axes` class, and is meant to be overridden by new kinds of projection axes that need different transformations and limits. (See :class:`~matplotlib.projections.polar.PolarAxes` for an example.
"""
# Transforms the x and y axis separately by a scale factor. # It is assumed that this part will have non-linear components # (e.g., for a log scale). mtransforms.IdentityTransform())
# An affine transformation on the data, generally to limit the # range of the axes mtransforms.TransformedBbox(self.viewLim, self.transScale))
# The parentheses are important for efficiency here -- they # group the last two (which are usually affines) separately # from the first (which, with log-scaling can be non-affine).
self.transData, self.transAxes) self.transAxes, self.transData)
""" Get the transformation used for drawing x-axis labels, ticks and gridlines. The x-direction is in data coordinates and the y-direction is in axis coordinates.
.. note::
This transformation is primarily used by the :class:`~matplotlib.axis.Axis` class, and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations.
""" # for cartesian projection, this is bottom spine # for cartesian projection, this is top spine else: raise ValueError('unknown value for which')
""" Get the transformation used for drawing x-axis labels, which will add the given amount of padding (in points) between the axes and the label. The x-direction is in data coordinates and the y-direction is in axis coordinates. Returns a 3-tuple of the form::
(transform, valign, halign)
where *valign* and *halign* are requested alignments for the text.
.. note::
This transformation is primarily used by the :class:`~matplotlib.axis.Axis` class, and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations.
"""
mtransforms.ScaledTranslation(0, -1 * pad_points / 72, self.figure.dpi_scale_trans), "top", labels_align)
""" Get the transformation used for drawing the secondary x-axis labels, which will add the given amount of padding (in points) between the axes and the label. The x-direction is in data coordinates and the y-direction is in axis coordinates. Returns a 3-tuple of the form::
(transform, valign, halign)
where *valign* and *halign* are requested alignments for the text.
.. note::
This transformation is primarily used by the :class:`~matplotlib.axis.Axis` class, and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations.
""" mtransforms.ScaledTranslation(0, pad_points / 72, self.figure.dpi_scale_trans), "bottom", labels_align)
""" Get the transformation used for drawing y-axis labels, ticks and gridlines. The x-direction is in axis coordinates and the y-direction is in data coordinates.
.. note::
This transformation is primarily used by the :class:`~matplotlib.axis.Axis` class, and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations.
""" # for cartesian projection, this is bottom spine # for cartesian projection, this is top spine else: raise ValueError('unknown value for which')
""" Get the transformation used for drawing y-axis labels, which will add the given amount of padding (in points) between the axes and the label. The x-direction is in axis coordinates and the y-direction is in data coordinates. Returns a 3-tuple of the form::
(transform, valign, halign)
where *valign* and *halign* are requested alignments for the text.
.. note::
This transformation is primarily used by the :class:`~matplotlib.axis.Axis` class, and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations.
""" mtransforms.ScaledTranslation(-1 * pad_points / 72, 0, self.figure.dpi_scale_trans), labels_align, "right")
""" Get the transformation used for drawing the secondary y-axis labels, which will add the given amount of padding (in points) between the axes and the label. The x-direction is in axis coordinates and the y-direction is in data coordinates. Returns a 3-tuple of the form::
(transform, valign, halign)
where *valign* and *halign* are requested alignments for the text.
.. note::
This transformation is primarily used by the :class:`~matplotlib.axis.Axis` class, and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations.
"""
mtransforms.ScaledTranslation(pad_points / 72, 0, self.figure.dpi_scale_trans), labels_align, "left")
mtransforms.blended_transform_factory( self.xaxis.get_transform(), self.yaxis.get_transform())) try: line._transformed_path.invalidate() except AttributeError: pass
""" Get a copy of the axes rectangle as a `.Bbox`.
Parameters ---------- original : bool If ``True``, return the original position. Otherwise return the active position. For an explanation of the positions see `.set_position`.
Returns ------- pos : `.Bbox`
""" else:
""" Set the axes position.
Axes have two position attributes. The 'original' position is the position allocated for the Axes. The 'active' position is the position the Axes is actually drawn at. These positions are usually the same unless a fixed aspect is set to the Axes. See `.set_aspect` for details.
Parameters ---------- pos : [left, bottom, width, height] or `~matplotlib.transforms.Bbox` The new position of the in `.Figure` coordinates.
which : {'both', 'active', 'original'}, optional Determines which position variables to change.
""" # because this is being called externally to the library we # zero the constrained layout parts.
""" private version of set_position. Call this internally to get the same functionality of `get_position`, but not to take the axis out of the constrained_layout hierarchy. """
""" Reset the active position to the original position.
This resets the a possible position change due to aspect constraints. For an explanation of the positions see `.set_position`. """ for ax in self._twinned_axes.get_siblings(self): pos = ax.get_position(original=True) ax.set_position(pos, which='active')
""" Set the axes locator.
Parameters ---------- locator : Callable[[Axes, Renderer], Bbox] """
""" Return the axes_locator. """
"""set the boilerplate props for artists added to axes"""
""" Returns the patch used to draw the background of the axes. It is also used as the clipping path for any data elements on the axes.
In the standard axes, this is a rectangle, but in other projections it may not be.
.. note::
Intended to be overridden by new projection types.
"""
""" Returns a dict whose keys are spine names and values are Line2D or Patch instances. Each element is used to draw a spine of the axes.
In the standard axes, this is a single line segment, but in other projections it may not be.
.. note::
Intended to be overridden by new projection types.
""" for side in ['left', 'right', 'bottom', 'top'])
"""Clear the current axes.""" # Note: this is called by Axes.__init__()
# stash the current visibility state else:
# major and minor are axis.Ticker class instances with # locator and formatter attributes auto=self._sharex.get_autoscalex_on()) self._sharex.xaxis.get_scale(), self.xaxis) else: except TypeError: pass
self.yaxis.major = self._sharey.yaxis.major self.yaxis.minor = self._sharey.yaxis.minor y0, y1 = self._sharey.get_ylim() self.set_ylim(y0, y1, emit=False, auto=self._sharey.get_autoscaley_on()) self.yaxis._scale = mscale.scale_factory( self._sharey.yaxis.get_scale(), self.yaxis) else: except TypeError: pass # update the minor locator for x and y axis based on rcParams self.xaxis.set_minor_locator(mticker.AutoMinorLocator())
self.yaxis.set_minor_locator(mticker.AutoMinorLocator())
axis=rcParams['axes.grid.axis']) size=rcParams['axes.titlesize'], weight=rcParams['axes.titleweight'])
x=0.5, y=1.0, text='', fontproperties=props, verticalalignment='baseline', horizontalalignment='center', ) x=0.0, y=1.0, text='', fontproperties=props.copy(), verticalalignment='baseline', horizontalalignment='left', ) x=1.0, y=1.0, text='', fontproperties=props.copy(), verticalalignment='baseline', horizontalalignment='right', ) # refactor this out so it can be called in ax.set_title if # pad argument used... # determine if the title position has been set manually:
# The patch draws the background of the axes. We want this to be below # the other artists. We use the frame to draw the edges so we are # setting the edgecolor to None.
self.yaxis.set_visible(yaxis_visible) self.patch.set_visible(patch_visible)
def mouseover_set(self): return frozenset(self._mouseover_set)
"""Clear the axes.""" self.cla()
"""Get the facecolor of the Axes.""" return self.patch.get_facecolor()
""" Set the facecolor of the Axes.
Parameters ---------- color : color """
""" Set the offset for the title either from rcParams['axes.titlepad'] or from set_title kwarg ``pad``. """ 0.0, title_offset_points / 72, self.figure.dpi_scale_trans)
""" Set the property cycle of the Axes.
The property cycle controls the style properties such as color, marker and linestyle of future plot commands. The style properties of data already added to the Axes are not modified.
Call signatures::
set_prop_cycle(cycler) set_prop_cycle(label=values[, label2=values2[, ...]]) set_prop_cycle(label, values)
Form 1 sets given `~cycler.Cycler` object.
Form 2 creates a `~cycler.Cycler` which cycles over one or more properties simultaneously and set it as the property cycle of the axes. If multiple properties are given, their value lists must have the same length. This is just a shortcut for explicitly creating a cycler and passing it to the function, i.e. it's short for ``set_prop_cycle(cycler(label=values label2=values2, ...))``.
Form 3 creates a `~cycler.Cycler` for a single property and set it as the property cycle of the axes. This form exists for compatibility with the original `cycler.cycler` interface. Its use is discouraged in favor of the kwarg form, i.e. ``set_prop_cycle(label=values)``.
Parameters ---------- cycler : Cycler Set the given Cycler. *None* resets to the cycle defined by the current style.
label : str The property key. Must be a valid `.Artist` property. For example, 'color' or 'linestyle'. Aliases are allowed, such as 'c' for 'color' and 'lw' for 'linewidth'.
values : iterable Finite-length iterable of the property values. These values are validated and will raise a ValueError if invalid.
Examples -------- Setting the property cycle for a single property:
>>> ax.set_prop_cycle(color=['red', 'green', 'blue'])
Setting the property cycle for simultaneously cycling over multiple properties (e.g. red circle, green plus, blue cross):
>>> ax.set_prop_cycle(color=['red', 'green', 'blue'], ... marker=['o', '+', 'x'])
See Also -------- matplotlib.rcsetup.cycler Convenience function for creating validated cyclers for properties. cycler.cycler The original function for creating unvalidated cyclers.
""" if args and kwargs: raise TypeError("Cannot supply both positional and keyword " "arguments to this method.") # Can't do `args == (None,)` as that crashes cycler. if len(args) == 1 and args[0] is None: prop_cycle = None else: prop_cycle = cycler(*args, **kwargs) self._get_lines.set_prop_cycle(prop_cycle) self._get_patches_for_fill.set_prop_cycle(prop_cycle)
""" Set the aspect of the axis scaling, i.e. the ratio of y-unit to x-unit.
Parameters ---------- aspect : {'auto', 'equal'} or num Possible values:
======== ================================================ value description ======== ================================================ 'auto' automatic; fill the position rectangle with data 'equal' same scaling from data to plot units for x and y num a circle will be stretched such that the height is num times the width. aspect=1 is the same as aspect='equal'. ======== ================================================
adjustable : None or {'box', 'datalim'}, optional If not ``None``, this defines which parameter will be adjusted to meet the required aspect. See `.set_adjustable` for further details.
anchor : None or str or 2-tuple of float, optional If not ``None``, this defines where the Axes will be drawn if there is extra space due to aspect constraints. The most common way to to specify the anchor are abbreviations of cardinal directions:
===== ===================== value description ===== ===================== 'C' centered 'SW' lower left corner 'S' middle of bottom edge 'SE' lower right corner etc. ===== =====================
See `.set_anchor` for further details.
share : bool, optional If ``True``, apply the settings to all shared Axes. Default is ``False``.
See Also -------- matplotlib.axes.Axes.set_adjustable defining the parameter to adjust in order to meet the required aspect. matplotlib.axes.Axes.set_anchor defining the position in case of extra space. """ aspect = float(aspect) # raise ValueError if necessary axes = set(self._shared_x_axes.get_siblings(self) + self._shared_y_axes.get_siblings(self)) else:
return self._adjustable
""" Define which parameter the Axes will change to achieve a given aspect.
Parameters ---------- adjustable : {'box', 'datalim'} If 'box', change the physical dimensions of the Axes. If 'datalim', change the ``x`` or ``y`` data limits.
share : bool, optional If ``True``, apply the settings to all shared Axes. Default is ``False``.
See Also -------- matplotlib.axes.Axes.set_aspect for a description of aspect handling.
Notes ----- Shared Axes (of which twinned Axes are a special case) impose restrictions on how aspect ratios can be imposed. For twinned Axes, use 'datalim'. For Axes that share both x and y, use 'box'. Otherwise, either 'datalim' or 'box' may be used. These limitations are partly a requirement to avoid over-specification, and partly a result of the particular implementation we are currently using, in which the adjustments for aspect ratios are done sequentially and independently on each Axes as it is drawn. """ cbook.warn_deprecated( "2.2", "box-forced", obj_type="keyword argument") raise ValueError("argument must be 'box', or 'datalim'") axes = set(self._shared_x_axes.get_siblings(self) + self._shared_y_axes.get_siblings(self)) else:
""" Get the anchor location.
See Also -------- matplotlib.axes.Axes.set_anchor for a description of the anchor. matplotlib.axes.Axes.set_aspect for a description of aspect handling. """
""" Define the anchor location.
The actual drawing area (active position) of the Axes may be smaller than the Bbox (original position) when a fixed aspect is required. The anchor defines where the drawing area will be located within the available space.
Parameters ---------- anchor : 2-tuple of floats or {'C', 'SW', 'S', 'SE', ...} The anchor position may be either:
- a sequence (*cx*, *cy*). *cx* and *cy* may range from 0 to 1, where 0 is left or bottom and 1 is right or top.
- a string using cardinal directions as abbreviation:
- 'C' for centered - 'S' (south) for bottom-center - 'SW' (south west) for bottom-left - etc.
Here is an overview of the possible positions:
+------+------+------+ | 'NW' | 'N' | 'NE' | +------+------+------+ | 'W' | 'C' | 'E' | +------+------+------+ | 'SW' | 'S' | 'SE' | +------+------+------+
share : bool, optional If ``True``, apply the settings to all shared Axes. Default is ``False``.
See Also -------- matplotlib.axes.Axes.set_aspect for a description of aspect handling. """ raise ValueError('argument must be among %s' % ', '.join(mtransforms.Bbox.coefs)) axes = set(self._shared_x_axes.get_siblings(self) + self._shared_y_axes.get_siblings(self)) else:
""" Returns the aspect ratio of the raw data.
This method is intended to be overridden by new projection types. """
""" Returns the aspect ratio of the raw data in log scale. Will be used when both axis scales are in log. """ xmin, xmax = self.get_xbound() ymin, ymax = self.get_ybound()
xsize = max(abs(math.log10(xmax) - math.log10(xmin)), 1e-30) ysize = max(abs(math.log10(ymax) - math.log10(ymin)), 1e-30)
return ysize / xsize
""" Adjust the Axes for a specified data aspect ratio.
Depending on `.get_adjustable` this will modify either the Axes box (position) or the view limits. In the former case, `.get_anchor` will affect the position.
Notes ----- This is called automatically when each Axes is drawn. You may need to call it yourself if you need to update the Axes position and/or view limits before the Figure is drawn.
See Also -------- matplotlib.axes.Axes.set_aspect for a description of aspect ratio handling. matplotlib.axes.Axes.set_adjustable defining the parameter to adjust in order to meet the required aspect. matplotlib.axes.Axes.set_anchor defining the position in case of extra space. """
elif xscale == "log" and yscale == "log": aspect_scale_mode = "log" elif ((xscale == "linear" and yscale == "log") or (xscale == "log" and yscale == "linear")): if aspect != "auto": warnings.warn( 'aspect is not supported for Axes with xscale=%s, ' 'yscale=%s' % (xscale, yscale), stacklevel=2) aspect = "auto" else: # some custom projections have their own scales. pass else:
else:
raise RuntimeError("Adjustable 'box' is not allowed in a" " twinned Axes. Use 'datalim' instead.") box_aspect = A * self.get_data_ratio_log() else:
# reset active to original in case it had been changed # by prior use of 'box' self._set_position(position, which='active')
xmin, xmax = self.get_xbound() ymin, ymax = self.get_ybound()
if aspect_scale_mode == "log": xmin, xmax = math.log10(xmin), math.log10(xmax) ymin, ymax = math.log10(ymin), math.log10(ymax)
xsize = max(abs(xmax - xmin), 1e-30) ysize = max(abs(ymax - ymin), 1e-30)
l, b, w, h = position.bounds box_aspect = fig_aspect * (h / w) data_ratio = box_aspect / A
y_expander = (data_ratio * xsize / ysize - 1.0) # If y_expander > 0, the dy/dx viewLim ratio needs to increase if abs(y_expander) < 0.005: return
if aspect_scale_mode == "log": dL = self.dataLim dL_width = math.log10(dL.x1) - math.log10(dL.x0) dL_height = math.log10(dL.y1) - math.log10(dL.y0) xr = 1.05 * dL_width yr = 1.05 * dL_height else: dL = self.dataLim xr = 1.05 * dL.width yr = 1.05 * dL.height
xmarg = xsize - xr ymarg = ysize - yr Ysize = data_ratio * xsize Xsize = ysize / data_ratio Xmarg = Xsize - xr Ymarg = Ysize - yr # Setting these targets to, e.g., 0.05*xr does not seem to # help. xm = 0 ym = 0
shared_x = self in self._shared_x_axes shared_y = self in self._shared_y_axes # Not sure whether we need this check: if shared_x and shared_y: raise RuntimeError("adjustable='datalim' is not allowed when both" " axes are shared.")
# If y is shared, then we are only allowed to change x, etc. if shared_y: adjust_y = False else: if xmarg > xm and ymarg > ym: adjy = ((Ymarg > 0 and y_expander < 0) or (Xmarg < 0 and y_expander > 0)) else: adjy = y_expander > 0 adjust_y = shared_x or adjy # (Ymarg > xmarg)
if adjust_y: yc = 0.5 * (ymin + ymax) y0 = yc - Ysize / 2.0 y1 = yc + Ysize / 2.0 if aspect_scale_mode == "log": self.set_ybound((10. ** y0, 10. ** y1)) else: self.set_ybound((y0, y1)) else: xc = 0.5 * (xmin + xmax) x0 = xc - Xsize / 2.0 x1 = xc + Xsize / 2.0 if aspect_scale_mode == "log": self.set_xbound((10. ** x0, 10. ** x1)) else: self.set_xbound((x0, x1))
""" Convenience method to get or set some axis properties.
Call signatures::
xmin, xmax, ymin, ymax = axis() xmin, xmax, ymin, ymax = axis(xmin, xmax, ymin, ymax) xmin, xmax, ymin, ymax = axis(option) xmin, xmax, ymin, ymax = axis(**kwargs)
Parameters ---------- xmin, ymin, xmax, ymax : float, optional The axis limits to be set. Either none or all of the limits must be given.
option : str Possible values:
======== ========================================================== Value Description ======== ========================================================== 'on' Turn on axis lines and labels. 'off' Turn off axis lines and labels. 'equal' Set equal scaling (i.e., make circles circular) by changing axis limits. 'scaled' Set equal scaling (i.e., make circles circular) by changing dimensions of the plot box. 'tight' Set limits just large enough to show all data. 'auto' Automatic scaling (fill plot box with data). 'normal' Same as 'auto'; deprecated. 'image' 'scaled' with axis limits equal to data limits. 'square' Square plot; similar to 'scaled', but initially forcing ``xmax-xmin = ymax-ymin``. ======== ==========================================================
emit : bool, optional, default *True* Whether observers are notified of the axis limit change. This option is passed on to `~.Axes.set_xlim` and `~.Axes.set_ylim`.
Returns ------- xmin, xmax, ymin, ymax : float The axis limits.
See also -------- matplotlib.axes.Axes.set_xlim matplotlib.axes.Axes.set_ylim """
if len(v) == len(kwargs) == 0: xmin, xmax = self.get_xlim() ymin, ymax = self.get_ylim() return xmin, xmax, ymin, ymax
emit = kwargs.get('emit', True)
if len(v) == 1 and isinstance(v[0], str): s = v[0].lower() if s == 'on': self.set_axis_on() elif s == 'off': self.set_axis_off() elif s in ('equal', 'tight', 'scaled', 'normal', 'auto', 'image', 'square'): self.set_autoscale_on(True) self.set_aspect('auto') self.autoscale_view(tight=False) # self.apply_aspect() if s == 'equal': self.set_aspect('equal', adjustable='datalim') elif s == 'scaled': self.set_aspect('equal', adjustable='box', anchor='C') self.set_autoscale_on(False) # Req. by Mark Bakker elif s == 'tight': self.autoscale_view(tight=True) self.set_autoscale_on(False) elif s == 'image': self.autoscale_view(tight=True) self.set_autoscale_on(False) self.set_aspect('equal', adjustable='box', anchor='C') elif s == 'square': self.set_aspect('equal', adjustable='box', anchor='C') self.set_autoscale_on(False) xlim = self.get_xlim() ylim = self.get_ylim() edge_size = max(np.diff(xlim), np.diff(ylim)) self.set_xlim([xlim[0], xlim[0] + edge_size], emit=emit, auto=False) self.set_ylim([ylim[0], ylim[0] + edge_size], emit=emit, auto=False) else: raise ValueError('Unrecognized string %s to axis; ' 'try on or off' % s) xmin, xmax = self.get_xlim() ymin, ymax = self.get_ylim() return xmin, xmax, ymin, ymax
try: v[0] except IndexError: xmin = kwargs.get('xmin', None) xmax = kwargs.get('xmax', None) auto = False # turn off autoscaling, unless... if xmin is None and xmax is None: auto = None # leave autoscaling state alone xmin, xmax = self.set_xlim(xmin, xmax, emit=emit, auto=auto)
ymin = kwargs.get('ymin', None) ymax = kwargs.get('ymax', None) auto = False # turn off autoscaling, unless... if ymin is None and ymax is None: auto = None # leave autoscaling state alone ymin, ymax = self.set_ylim(ymin, ymax, emit=emit, auto=auto) return xmin, xmax, ymin, ymax
v = v[0] if len(v) != 4: raise ValueError('v must contain [xmin xmax ymin ymax]')
self.set_xlim([v[0], v[1]], emit=emit, auto=False) self.set_ylim([v[2], v[3]], emit=emit, auto=False)
return v
"""Return the `Legend` instance, or None if no legend is defined.""" return self.legend_
"""return a list of Axes images contained by the Axes""" return cbook.silent_list('AxesImage', self.images)
"""Return a list of lines contained by the Axes""" return cbook.silent_list('Line2D', self.lines)
"""Return the XAxis instance."""
"""Get the x grid lines as a list of `Line2D` instances.""" return cbook.silent_list('Line2D xgridline', self.xaxis.get_gridlines())
"""Get the x tick lines as a list of `Line2D` instances.""" return cbook.silent_list('Line2D xtickline', self.xaxis.get_ticklines())
"""Return the YAxis instance."""
"""Get the y grid lines as a list of `Line2D` instances.""" return cbook.silent_list('Line2D ygridline', self.yaxis.get_gridlines())
"""Get the y tick lines as a list of `Line2D` instances.""" return cbook.silent_list('Line2D ytickline', self.yaxis.get_ticklines())
# Adding and tracking artists
"""Set the current image.
This image will be the target of colormap functions like `~.pyplot.viridis`, and other functions such as `~.pyplot.clim`. The current image is an attribute of the current axes. """ if isinstance(im, matplotlib.contour.ContourSet): if im.collections[0] not in self.collections: raise ValueError("ContourSet must be in current Axes") elif im not in self.images and im not in self.collections: raise ValueError("Argument must be an image, collection, or " "ContourSet in this Axes") self._current_image = im
""" Helper for :func:`~matplotlib.pyplot.gci`; do not use elsewhere. """ return self._current_image
""" Return *True* if any artists have been added to axes.
This should not be used to determine whether the *dataLim* need to be updated, and may not actually be useful for anything. """ return ( len(self.collections) + len(self.images) + len(self.lines) + len(self.patches)) > 0
"""Add any :class:`~matplotlib.artist.Artist` to the axes.
Use `add_artist` only for artists for which there is no dedicated "add" method; and if necessary, use a method such as `update_datalim` to manually update the dataLim if the artist is to be included in autoscaling.
If no ``transform`` has been specified when creating the artist (e.g. ``artist.get_transform() == None``) then the transform is set to ``ax.transData``.
Returns the artist. """
""" Add a :class:`~matplotlib.axes.Axesbase` instance as a child to the axes.
Returns the added axes.
This is the lowlevel version. See `.axes.Axes.inset_axes` """
# normally axes have themselves as the axes, but these need to have # their parent... # Need to bypass the getter... ax._axes = self ax.stale_callback = martist._stale_axes_callback
self.child_axes.append(ax) ax._remove_method = self.child_axes.remove self.stale = True return ax
""" Add a :class:`~matplotlib.collections.Collection` instance to the axes.
Returns the collection. """
""" Add a :class:`~matplotlib.image.AxesImage` to the axes.
Returns the image. """
xmin, xmax, ymin, ymax = image.get_extent() self.axes.update_datalim(((xmin, ymin), (xmax, ymax)))
""" Add a :class:`~matplotlib.lines.Line2D` to the list of plot lines
Returns the line. """
"""
"""
""" Figures out the data limit of the given line, updating self.dataLim. """ return
# identify the transform to go from line's coordinates # to data coordinates
# if transData is affine we can use the cached non-affine component # of line's path. (since the non-affine part of line_trans is # entirely encapsulated in trans_to_data). else: data_path = trans_to_data.transform_path(path) else: # for backwards compatibility we update the dataLim with the # coordinate range of the given path, even though the coordinate # systems are completely different. This may occur in situations # such as when ax.transAxes is passed through for absolute # positioning. data_path = path
self.transData) self.ignore_existing_data_limits, updatex=updatex, updatey=updatey)
""" Add a :class:`~matplotlib.patches.Patch` *p* to the list of axes patches; the clipbox will be set to the Axes clipping box. If the transform is not set, it will be set to :attr:`transData`.
Returns the patch. """
"""update the data limits for patch *p*""" # hist can add zero height Rectangles, which is useful to keep # the bins, counts and patches lined up, but it throws off log # scaling. We'll ignore rects with zero height or width in # the auto-scaling
# cannot check for '==0' since unitized data may not compare to zero # issue #2150 - we update the limits if patch has non zero width # or height. ((not patch.get_width()) and (not patch.get_height()))): return self.transData)
contains_branch_seperately(self.transData) updatey=updatey)
""" Add a :class:`~matplotlib.table.Table` instance to the list of axes tables
Parameters ---------- tab: `matplotlib.table.Table` Table instance
Returns ------- `matplotlib.table.Table`: the table. """ self._set_artist_props(tab) self.tables.append(tab) tab.set_clip_path(self.patch) tab._remove_method = self.tables.remove return tab
""" Add a :class:`~matplotlib.container.Container` instance to the axes.
Returns the collection. """ label = container.get_label() if not label: container.set_label('_container%d' % len(self.containers)) self.containers.append(container) container._remove_method = self.containers.remove return container
""" Callback for processing changes to axis units.
Currently forces updates of data limits and view limits. """ self.relim() self.autoscale_view(scalex=scalex, scaley=scaley)
""" Recompute the data limits based on current artists. If you want to exclude invisible artists from the calculation, set ``visible_only=True``
At present, :class:`~matplotlib.collections.Collection` instances are not supported. """ # Collections are deliberately not supported (yet); see # the TODO note in artists.py. self.dataLim.ignore(True) self.dataLim.set_points(mtransforms.Bbox.null().get_points()) self.ignore_existing_data_limits = True
for line in self.lines: if not visible_only or line.get_visible(): self._update_line_limits(line)
for p in self.patches: if not visible_only or p.get_visible(): self._update_patch_limits(p)
for image in self.images: if not visible_only or image.get_visible(): self._update_image_limits(image)
""" Extend the `~.Axes.dataLim` BBox to include the given points.
If no data is set currently, the BBox will ignore its limits and set the bound to be the bounds of the xydata (*xys*). Otherwise, it will compute the bounds of the union of its current data and the data in *xys*.
Parameters ---------- xys : 2D array-like The points to include in the data limits BBox. This can be either a list of (x, y) tuples or a Nx2 array.
updatex, updatey : bool, optional, default *True* Whether to update the x/y limits. """ return updatex=updatex, updatey=updatey)
""" Extend the `~.Axes.datalim` BBox to include the given `~matplotlib.transforms.Bbox`.
Parameters ---------- bounds : `~matplotlib.transforms.Bbox` """ self.dataLim.set(mtransforms.Bbox.union([self.dataLim, bounds]))
"""Look for unit *kwargs* and update the axis instances as necessary"""
# Return if there's no axis set return kwargs
# We only need to update if there is nothing set yet.
# Check for units in the kwargs, and if present update axis
axis.set_units(units) # If the units being set imply a different converter, # we need to update. if data is not None: axis.update_units(data)
""" Return *True* if the given *mouseevent* (in display coords) is in the Axes """ return self.patch.contains(mouseevent)[0]
""" Get whether autoscaling is applied for both axes on plot commands """ return self._autoscaleXon and self._autoscaleYon
""" Get whether autoscaling for the x-axis is applied on plot commands """
""" Get whether autoscaling for the y-axis is applied on plot commands """ return self._autoscaleYon
""" Set whether autoscaling is applied on plot commands
Parameters ---------- b : bool """ self._autoscaleXon = b self._autoscaleYon = b
""" Set whether autoscaling for the x-axis is applied on plot commands
Parameters ---------- b : bool """
""" Set whether autoscaling for the y-axis is applied on plot commands
Parameters ---------- b : bool """ self._autoscaleYon = b
def use_sticky_edges(self): """ When autoscaling, whether to obey all `Artist.sticky_edges`.
Default is ``True``.
Setting this to ``False`` ensures that the specified margins will be applied, even if the plot includes an image, for example, which would otherwise force a view limit to coincide with its data limit.
The changing this property does not change the plot until `autoscale` or `autoscale_view` is called. """
def use_sticky_edges(self, b): # No effect until next autoscaling, which will mark the axes as stale.
""" Set padding of X data limits prior to autoscaling.
*m* times the data interval will be added to each end of that interval before it is used in autoscaling. For example, if your data is in the range [0, 2], a factor of ``m = 0.1`` will result in a range [-0.2, 2.2].
Negative values -0.5 < m < 0 will result in clipping of the data range. I.e. for a data range [0, 2], a factor of ``m = -0.1`` will result in a range [0.2, 1.8].
Parameters ---------- m : float greater than -0.5 """ if m <= -0.5: raise ValueError("margin must be greater than -0.5") self._xmargin = m self.stale = True
""" Set padding of Y data limits prior to autoscaling.
*m* times the data interval will be added to each end of that interval before it is used in autoscaling. For example, if your data is in the range [0, 2], a factor of ``m = 0.1`` will result in a range [-0.2, 2.2].
Negative values -0.5 < m < 0 will result in clipping of the data range. I.e. for a data range [0, 2], a factor of ``m = -0.1`` will result in a range [0.2, 1.8].
Parameters ---------- m : float greater than -0.5 """ if m <= -0.5: raise ValueError("margin must be greater than -0.5") self._ymargin = m self.stale = True
""" Set or retrieve autoscaling margins.
The padding added to each limit of the axes is the *margin* times the data interval. All input parameters must be floats within the range [0, 1]. Passing both positional and keyword arguments is invalid and will raise a TypeError. If no arguments (positional or otherwise) are provided, the current margins will remain in place and simply be returned.
Specifying any margin changes only the autoscaling; for example, if *xmargin* is not None, then *xmargin* times the X data interval will be added to each end of that interval before it is used in autoscaling.
Parameters ---------- args : float, optional If a single positional argument is provided, it specifies both margins of the x-axis and y-axis limits. If two positional arguments are provided, they will be interpreted as *xmargin*, *ymargin*. If setting the margin on a single axis is desired, use the keyword arguments described below.
x, y : float, optional Specific margin values for the x-axis and y-axis, respectively. These cannot be used with positional arguments, but can be used individually to alter on e.g., only the y-axis.
tight : bool, default is True The *tight* parameter is passed to :meth:`autoscale_view`, which is executed after a margin is changed; the default here is *True*, on the assumption that when margins are specified, no additional padding to match tick marks is usually desired. Set *tight* to *None* will preserve the previous setting.
Returns ------- xmargin, ymargin : float
Notes ----- If a previously used Axes method such as :meth:`pcolor` has set :attr:`use_sticky_edges` to `True`, only the limits not set by the "sticky artists" will be modified. To force all of the margins to be set, set :attr:`use_sticky_edges` to `False` before calling :meth:`margins`.
"""
if margins and x is not None and y is not None: raise TypeError('Cannot pass both positional and keyword ' 'arguments for x and/or y.') elif len(margins) == 1: x = y = margins[0] elif len(margins) == 2: x, y = margins elif margins: raise TypeError('Must pass a single positional argument for all ' 'margins, or one for each margin (x, y).')
if x is None and y is None: if tight is not True: warnings.warn('ignoring tight=%r in get mode' % (tight,), stacklevel=2) return self._xmargin, self._ymargin
if x is not None: self.set_xmargin(x) if y is not None: self.set_ymargin(y)
self.autoscale_view( tight=tight, scalex=(x is not None), scaley=(y is not None) )
""" Parameters ---------- z : float or None zorder below which artists are rasterized. ``None`` means that artists do not get rasterized based on zorder. """ self._rasterization_zorder = z self.stale = True
"""Return the zorder value below which artists will be rasterized.""" return self._rasterization_zorder
""" Autoscale the axis view to the data (toggle).
Convenience method for simple axis view autoscaling. It turns autoscaling on or off, and then, if autoscaling for either axis is on, it performs the autoscaling on the specified axis or axes.
Parameters ---------- enable : bool or None, optional True (default) turns autoscaling on, False turns it off. None leaves the autoscaling state unchanged.
axis : {'both', 'x', 'y'}, optional which axis to operate on; default is 'both'
tight: bool or None, optional If True, set view limits to data limits; if False, let the locator and margins expand the view limits; if None, use tight scaling if the only artist is an image, otherwise treat *tight* as False. The *tight* setting is retained for future autoscaling until it is explicitly changed.
""" if enable is None: scalex = True scaley = True else: scalex = False scaley = False if axis in ['x', 'both']: self._autoscaleXon = bool(enable) scalex = self._autoscaleXon if axis in ['y', 'both']: self._autoscaleYon = bool(enable) scaley = self._autoscaleYon if tight and scalex: self._xmargin = 0 if tight and scaley: self._ymargin = 0 self.autoscale_view(tight=tight, scalex=scalex, scaley=scaley)
""" Autoscale the view limits using the data limits.
You can selectively autoscale only a single axis, e.g., the xaxis by setting *scaley* to *False*. The autoscaling preserves any axis direction reversal that has already been done.
If *tight* is *False*, the axis major locator will be used to expand the view limits if rcParams['axes.autolimit_mode'] is 'round_numbers'. Note that any margins that are in effect will be applied first, regardless of whether *tight* is *True* or *False*. Specifying *tight* as *True* or *False* saves the setting as a private attribute of the Axes; specifying it as *None* (the default) applies the previously saved value.
The data limits are not updated automatically when artist data are changed after the artist has been added to an Axes instance. In that case, use :meth:`matplotlib.axes.Axes.relim` prior to calling autoscale_view. """
x_stickies = [xs for xs in x_stickies if xs > 0] y_stickies = [ys for ys in y_stickies if ys > 0] else: # Small optimization. x_stickies, y_stickies = [], []
minpos, axis, margin, stickies, set_bound):
# ignore non-finite data limits if good limits exist # if finite limits exist for atleast one axis (and the # other is infinite), restore the finite limits if (np.isfinite(d.intervalx).all() and (d not in finite_dl))] if (np.isfinite(d.intervaly).all() and (d not in finite_dl))]
# e.g., DateLocator has its own nonsingular() # Default nonsingular for, e.g., MaxNLocator x0, x1, increasing=False, expander=0.05)
# Add the margin in figure space and then transform back, to handle # non-linear scales. # We cannot use exact equality due to floating point issues e.g. # with streamplot.
else: # If at least one bound isn't finite, set margin to zero delta = 0
# End of definition of internal function 'handle_single_axis'.
scalex, self._autoscaleXon, self._shared_x_axes, 'intervalx', 'minposx', self.xaxis, self._xmargin, x_stickies, self.set_xbound) scaley, self._autoscaleYon, self._shared_y_axes, 'intervaly', 'minposy', self.yaxis, self._ymargin, y_stickies, self.set_ybound)
""" Update the title position based on the bounding box enclosing all the ticklabels and x-axis spine and xlabel... """
_log.debug('title position was updated manually, not adjusting') return
' already placed manually: %f', y)
# need to check all our twins too...
or ax.xaxis.get_ticks_position() == 'top'): bb = ax.xaxis.get_tightbbox(renderer) top = bb.ymax # we don't need to pad because the padding is already # in __init__: titleOffsetTrans yn = self.transAxes.inverted().transform((0., top))[1] y = max(y, yn) except AttributeError: pass
# Drawing
"""Draw everything (plot lines, axes, labels)""" renderer = self._cachedRenderer
raise RuntimeError('No renderer defined') return
# prevent triggering call backs during the draw process pos = locator(self, renderer) self.apply_aspect(pos) else:
# the frame draws the edges around the axes patch -- we # decouple these so the patch can be in the background and the # frame in the foreground. Do this before drawing the axis # objects so that the spine has the opportunity to update them.
artists.remove(self.title) artists.remove(self._left_title) artists.remove(self._right_title)
artists = [a for a in artists if not a.get_animated() or a in self.images]
# rasterize artists with negative zorder # if the minimum zorder is negative, start rasterization
artists and artists[0].zorder < rasterization_zorder): renderer.start_rasterizing() artists_rasterized = [a for a in artists if a.zorder < rasterization_zorder] artists = [a for a in artists if a.zorder >= rasterization_zorder] else:
# the patch draws the background rectangle -- the frame below # will draw the edges
for a in artists_rasterized: a.draw(renderer) renderer.stop_rasterizing()
""" This method can only be used after an initial draw which caches the renderer. It is used to efficiently update Axes data (axis ticks, labels, etc are not updated) """ if self._cachedRenderer is None: raise AttributeError("draw_artist can only be used after an " "initial draw which caches the renderer") a.draw(self._cachedRenderer)
""" This method can only be used after an initial draw which caches the renderer. It is used to efficiently update Axes data (axis ticks, labels, etc are not updated) """ if self._cachedRenderer is None: raise AttributeError("redraw_in_frame can only be used after an " "initial draw which caches the renderer") self.draw(self._cachedRenderer, inframe=True)
return self._cachedRenderer
# Axes rectangle characteristics
"""Get whether the axes rectangle patch is drawn.""" return self._frameon
""" Set whether the axes rectangle patch is drawn.
Parameters ---------- b : bool """
""" Get whether axis ticks and gridlines are above or below most artists.
Returns ------- axisbelow : bool or 'line'
See Also -------- set_axisbelow """ return self._axisbelow
""" Set whether axis ticks and gridlines are above or below most artists.
This controls the zorder of the ticks and gridlines. For more information on the zorder see :doc:`/gallery/misc/zorder_demo`.
Parameters ---------- b : bool or 'line' Possible values:
- *True* (zorder = 0.5): Ticks and gridlines are below all Artists. - 'line' (zorder = 1.5): Ticks and gridlines are above patches ( e.g. rectangles) but still below lines / markers. - *False* (zorder = 2.5): Ticks and gridlines are above patches and lines / markers.
See Also -------- get_axisbelow """ zorder = 0.5 zorder = 2.5 else: raise ValueError("Unexpected axisbelow value")
""" Configure the grid lines.
Parameters ---------- b : bool or None Whether to show the grid lines. If any *kwargs* are supplied, it is assumed you want the grid on and *b* will be set to True.
If *b* is *None* and there are no *kwargs*, this toggles the visibility of the lines.
which : {'major', 'minor', 'both'} The grid lines to apply the changes on.
axis : {'both', 'x', 'y'} The axis to apply the changes on.
**kwargs : `.Line2D` properties Define the line properties of the grid, e.g.::
grid(color='r', linestyle='-', linewidth=2)
Valid *kwargs* are
%(Line2D)s
Notes ----- The grid will be drawn according to the axes' zorder and not its own. """
useOffset=None, useLocale=None, useMathText=None): r""" Change the `~matplotlib.ticker.ScalarFormatter` used by default for linear axes.
Optional keyword arguments:
============== ========================================= Keyword Description ============== ========================================= *axis* [ 'x' | 'y' | 'both' ] *style* [ 'sci' (or 'scientific') | 'plain' ] plain turns off scientific notation *scilimits* (m, n), pair of integers; if *style* is 'sci', scientific notation will be used for numbers outside the range 10\ :sup:`m` to 10\ :sup:`n`. Use (0,0) to include all numbers. Use (m,m) where m <> 0 to fix the order of magnitude to 10\ :sup:`m`. *useOffset* [ bool | offset ]; if True, the offset will be calculated as needed; if False, no offset will be used; if a numeric offset is specified, it will be used. *useLocale* If True, format the number according to the current locale. This affects things such as the character used for the decimal separator. If False, use C-style (English) formatting. The default setting is controlled by the axes.formatter.use_locale rcparam. *useMathText* If True, render the offset and scientific notation in mathtext ============== =========================================
Only the major ticks are affected. If the method is called when the :class:`~matplotlib.ticker.ScalarFormatter` is not the :class:`~matplotlib.ticker.Formatter` being used, an :exc:`AttributeError` will be raised.
""" style = style.lower() axis = axis.lower() if scilimits is not None: try: m, n = scilimits m + n + 1 # check that both are numbers except (ValueError, TypeError): raise ValueError("scilimits must be a sequence of 2 integers") if style[:3] == 'sci': sb = True elif style == 'plain': sb = False elif style == '': sb = None else: raise ValueError("%s is not a valid style value") try: if sb is not None: if axis == 'both' or axis == 'x': self.xaxis.major.formatter.set_scientific(sb) if axis == 'both' or axis == 'y': self.yaxis.major.formatter.set_scientific(sb) if scilimits is not None: if axis == 'both' or axis == 'x': self.xaxis.major.formatter.set_powerlimits(scilimits) if axis == 'both' or axis == 'y': self.yaxis.major.formatter.set_powerlimits(scilimits) if useOffset is not None: if axis == 'both' or axis == 'x': self.xaxis.major.formatter.set_useOffset(useOffset) if axis == 'both' or axis == 'y': self.yaxis.major.formatter.set_useOffset(useOffset) if useLocale is not None: if axis == 'both' or axis == 'x': self.xaxis.major.formatter.set_useLocale(useLocale) if axis == 'both' or axis == 'y': self.yaxis.major.formatter.set_useLocale(useLocale) if useMathText is not None: if axis == 'both' or axis == 'x': self.xaxis.major.formatter.set_useMathText(useMathText) if axis == 'both' or axis == 'y': self.yaxis.major.formatter.set_useMathText(useMathText) except AttributeError: raise AttributeError( "This method only works with the ScalarFormatter.")
""" Control behavior of tick locators.
Parameters ---------- axis : {'both', 'x', 'y'}, optional The axis on which to operate.
tight : bool or None, optional Parameter passed to :meth:`autoscale_view`. Default is None, for no change.
Other Parameters ---------------- **kw : Remaining keyword arguments are passed to directly to the :meth:`~matplotlib.ticker.MaxNLocator.set_params` method.
Typically one might want to reduce the maximum number of ticks and use tight bounds when plotting small subplots, for example::
ax.locator_params(tight=True, nbins=4)
Because the locator is involved in autoscaling, :meth:`autoscale_view` is called automatically after the parameters are changed.
This presently works only for the :class:`~matplotlib.ticker.MaxNLocator` used by default on linear axes, but it may be generalized. """ _x = axis in ['x', 'both'] _y = axis in ['y', 'both'] if _x: self.xaxis.get_major_locator().set_params(**kwargs) if _y: self.yaxis.get_major_locator().set_params(**kwargs) self.autoscale_view(tight=tight, scalex=_x, scaley=_y)
"""Change the appearance of ticks, tick labels, and gridlines.
Parameters ---------- axis : {'x', 'y', 'both'}, optional Which axis to apply the parameters to.
Other Parameters ----------------
axis : {'x', 'y', 'both'} Axis on which to operate; default is 'both'.
reset : bool If *True*, set all parameters to defaults before processing other keyword arguments. Default is *False*.
which : {'major', 'minor', 'both'} Default is 'major'; apply arguments to *which* ticks.
direction : {'in', 'out', 'inout'} Puts ticks inside the axes, outside the axes, or both.
length : float Tick length in points.
width : float Tick width in points.
color : color Tick color; accepts any mpl color spec.
pad : float Distance in points between tick and label.
labelsize : float or str Tick label font size in points or as a string (e.g., 'large').
labelcolor : color Tick label color; mpl color spec.
colors : color Changes the tick color and the label color to the same value: mpl color spec.
zorder : float Tick and label zorder.
bottom, top, left, right : bool Whether to draw the respective ticks.
labelbottom, labeltop, labelleft, labelright : bool Whether to draw the respective tick labels.
labelrotation : float Tick label rotation
grid_color : color Changes the gridline color to the given mpl color spec.
grid_alpha : float Transparency of gridlines: 0 (transparent) to 1 (opaque).
grid_linewidth : float Width of gridlines in points.
grid_linestyle : string Any valid :class:`~matplotlib.lines.Line2D` line style spec.
Examples --------
Usage ::
ax.tick_params(direction='out', length=6, width=2, colors='r', grid_color='r', grid_alpha=0.5)
This will make all major ticks be red, pointing out of the box, and with dimensions 6 points by 2 points. Tick labels will also be red. Gridlines will be red and translucent.
"""
""" Turn the x- and y-axis off.
This affects the axis lines, ticks, ticklabels, grid and axis labels. """
""" Turn the x- and y-axis on.
This affects the axis lines, ticks, ticklabels, grid and axis labels. """
# data limits, ticks, tick labels, and formatting
""" Invert the x-axis.
See Also -------- xaxis_inverted get_xlim, set_xlim get_xbound, set_xbound """ self.set_xlim(self.get_xlim()[::-1], auto=None)
""" Return whether the x-axis is inverted.
The axis is inverted if the left value is larger than the right value.
See Also -------- invert_xaxis get_xlim, set_xlim get_xbound, set_xbound """
""" Return the lower and upper x-axis bounds, in increasing order.
See Also -------- set_xbound get_xlim, set_xlim invert_xaxis, xaxis_inverted """ else: return right, left
""" Set the lower and upper numerical bounds of the x-axis.
This method will honor axes inversion regardless of parameter order. It will not change the autoscaling setting (``Axes._autoscaleXon``).
Parameters ---------- lower, upper : float or None The lower and upper bounds. If *None*, the respective axis bound is not modified.
See Also -------- get_xbound get_xlim, set_xlim invert_xaxis, xaxis_inverted """ lower, upper = lower
lower = old_lower upper = old_upper
if lower < upper: self.set_xlim(upper, lower, auto=None) else: self.set_xlim(lower, upper, auto=None) else: else: self.set_xlim(upper, lower, auto=None)
""" Return the x-axis view limits.
Returns ------- left, right : (float, float) The current x-axis limits in data coordinates.
See Also -------- set_xlim set_xbound, get_xbound invert_xaxis, xaxis_inverted
Notes ----- The x-axis may be inverted, in which case the *left* value will be greater than the *right* value.
"""
""" Raise ValueError if converted limits are non-finite.
Note that this function also accepts None as a limit argument.
Returns ------- The limit value after call to convert(), or None if limit is None.
""" and not np.isfinite(converted_limit)): raise ValueError("Axis limits cannot be NaN or Inf")
*, xmin=None, xmax=None): """ Set the x-axis view limits.
.. ACCEPTS: (left: float, right: float)
Parameters ---------- left : scalar, optional The left xlim in data coordinates. Passing *None* leaves the limit unchanged.
The left and right xlims may be passed as the tuple (`left`, `right`) as the first positional argument (or as the `left` keyword argument).
right : scalar, optional The right xlim in data coordinates. Passing *None* leaves the limit unchanged.
emit : bool, optional Whether to notify observers of limit change (default: True).
auto : bool or None, optional Whether to turn on autoscaling of the x-axis. True turns on, False turns off (default action), None leaves unchanged.
xmin, xmax : scalar, optional These arguments are deprecated and will be removed in a future version. They are equivalent to left and right respectively, and it is an error to pass both *xmin* and *left* or *xmax* and *right*.
Returns ------- left, right : (float, float) The new x-axis limits in data coordinates.
See Also -------- get_xlim set_xbound, get_xbound invert_xaxis, xaxis_inverted
Notes ----- The *left* value may be greater than the *right* value, in which case the x-axis values will decrease from left to right.
Examples -------- >>> set_xlim(left, right) >>> set_xlim((left, right)) >>> left, right = set_xlim(left, right)
One limit may be left unchanged.
>>> set_xlim(right=right_lim)
Limits may be passed in reverse order to flip the direction of the x-axis. For example, suppose ``x`` represents the number of years before present. The x-axis limits might be set like the following so 5000 years ago is on the left of the plot and the present is on the right.
>>> set_xlim(5000, 0)
""" cbook.warn_deprecated('3.0', name='`xmin`', alternative='`left`', obj_type='argument') if left is not None: raise TypeError('Cannot pass both `xmin` and `left`') left = xmin cbook.warn_deprecated('3.0', name='`xmax`', alternative='`right`', obj_type='argument') if right is not None: raise TypeError('Cannot pass both `xmax` and `right`') right = xmax
left = old_left right = old_right
warnings.warn( ('Attempting to set identical left==right results\n' 'in singular transformations; automatically expanding.\n' 'left=%s, right=%s') % (left, right), stacklevel=2)
if left <= 0: warnings.warn( 'Attempted to set non-positive left xlim on a ' 'log-scaled axis.\n' 'Invalid limit will be ignored.', stacklevel=2) left = old_left if right <= 0: warnings.warn( 'Attempted to set non-positive right xlim on a ' 'log-scaled axis.\n' 'Invalid limit will be ignored.', stacklevel=2) right = old_right
# Call all of the other x-axes that are shared with this one emit=False, auto=auto) other.figure.canvas is not None): other.figure.canvas.draw_idle()
""" Return the x-axis scale as string.
See Also -------- set_xscale """
""" Set the x-axis scale.
Parameters ---------- value : {"linear", "log", "symlog", "logit", ...} The axis scale type to apply.
**kwargs Different keyword arguments are accepted, depending on the scale. See the respective class keyword arguments:
- `matplotlib.scale.LinearScale` - `matplotlib.scale.LogScale` - `matplotlib.scale.SymmetricalLogScale` - `matplotlib.scale.LogitScale`
Notes ----- By default, Matplotlib supports the above mentioned scales. Additionally, custom scales may be registered using `matplotlib.scale.register_scale`. These scales can then also be used here. """ g = self.get_shared_x_axes() for ax in g.get_siblings(self): ax.xaxis._set_scale(value, **kwargs) ax._update_transScale() ax.stale = True
self.autoscale_view(scaley=False)
"""Return the x ticks as a list of locations""" return self.xaxis.get_ticklocs(minor=minor)
""" Set the x ticks with list of *ticks*
Parameters ---------- ticks : list List of x-axis tick locations.
minor : bool, optional If ``False`` sets major ticks, if ``True`` sets minor ticks. Default is ``False``. """ ret = self.xaxis.set_ticks(ticks, minor=minor) self.stale = True return ret
""" Get the major x tick labels.
Returns ------- labels : list List of :class:`~matplotlib.text.Text` instances """ return cbook.silent_list('Text xticklabel', self.xaxis.get_majorticklabels())
""" Get the minor x tick labels.
Returns ------- labels : list List of :class:`~matplotlib.text.Text` instances """ return cbook.silent_list('Text xticklabel', self.xaxis.get_minorticklabels())
""" Get the x tick labels as a list of :class:`~matplotlib.text.Text` instances.
Parameters ---------- minor : bool, optional If True return the minor ticklabels, else return the major ticklabels.
which : None, ('minor', 'major', 'both') Overrides `minor`.
Selects which ticklabels to return
Returns ------- ret : list List of :class:`~matplotlib.text.Text` instances. """ return cbook.silent_list('Text xticklabel', self.xaxis.get_ticklabels(minor=minor, which=which))
""" Set the x-tick labels with list of string labels.
Parameters ---------- labels : List[str] List of string labels.
fontdict : dict, optional A dictionary controlling the appearance of the ticklabels. The default `fontdict` is::
{'fontsize': rcParams['axes.titlesize'], 'fontweight': rcParams['axes.titleweight'], 'verticalalignment': 'baseline', 'horizontalalignment': loc}
minor : bool, optional Whether to set the minor ticklabels rather than the major ones.
Returns ------- A list of `~.text.Text` instances.
Other Parameters ----------------- **kwargs : `~.text.Text` properties. """ if fontdict is not None: kwargs.update(fontdict) ret = self.xaxis.set_ticklabels(labels, minor=minor, **kwargs) self.stale = True return ret
""" Invert the y-axis.
See Also -------- yaxis_inverted get_ylim, set_ylim get_ybound, set_ybound """ self.set_ylim(self.get_ylim()[::-1], auto=None)
""" Return whether the y-axis is inverted.
The axis is inverted if the bottom value is larger than the top value.
See Also -------- invert_yaxis get_ylim, set_ylim get_ybound, set_ybound """
""" Return the lower and upper y-axis bounds, in increasing order.
See Also -------- set_ybound get_ylim, set_ylim invert_yaxis, yaxis_inverted """ else:
""" Set the lower and upper numerical bounds of the y-axis.
This method will honor axes inversion regardless of parameter order. It will not change the autoscaling setting (``Axes._autoscaleYon``).
Parameters ---------- lower, upper : float or None The lower and upper bounds. If *None*, the respective axis bound is not modified.
See Also -------- get_ybound get_ylim, set_ylim invert_yaxis, yaxis_inverted """ lower, upper = lower
lower = old_lower upper = old_upper
else: self.set_ylim(lower, upper, auto=None) else: else: self.set_ylim(upper, lower, auto=None)
""" Return the y-axis view limits.
Returns ------- bottom, top : (float, float) The current y-axis limits in data coordinates.
See Also -------- set_ylim set_ybound, get_ybound invert_yaxis, yaxis_inverted
Notes ----- The y-axis may be inverted, in which case the *bottom* value will be greater than the *top* value.
"""
*, ymin=None, ymax=None): """ Set the y-axis view limits.
.. ACCEPTS: (bottom: float, top: float)
Parameters ---------- bottom : scalar, optional The bottom ylim in data coordinates. Passing *None* leaves the limit unchanged.
The bottom and top ylims may be passed as the tuple (`bottom`, `top`) as the first positional argument (or as the `bottom` keyword argument).
top : scalar, optional The top ylim in data coordinates. Passing *None* leaves the limit unchanged.
emit : bool, optional Whether to notify observers of limit change (default: True).
auto : bool or None, optional Whether to turn on autoscaling of the y-axis. *True* turns on, *False* turns off (default action), *None* leaves unchanged.
ymin, ymax : scalar, optional These arguments are deprecated and will be removed in a future version. They are equivalent to bottom and top respectively, and it is an error to pass both *ymin* and *bottom* or *ymax* and *top*.
Returns ------- bottom, top : (float, float) The new y-axis limits in data coordinates.
See Also -------- get_ylim set_ybound, get_ybound invert_yaxis, yaxis_inverted
Notes ----- The *bottom* value may be greater than the *top* value, in which case the y-axis values will decrease from *bottom* to *top*.
Examples -------- >>> set_ylim(bottom, top) >>> set_ylim((bottom, top)) >>> bottom, top = set_ylim(bottom, top)
One limit may be left unchanged.
>>> set_ylim(top=top_lim)
Limits may be passed in reverse order to flip the direction of the y-axis. For example, suppose ``y`` represents depth of the ocean in m. The y-axis limits might be set like the following so 5000 m depth is at the bottom of the plot and the surface, 0 m, is at the top.
>>> set_ylim(5000, 0) """ cbook.warn_deprecated('3.0', name='`ymin`', alternative='`bottom`', obj_type='argument') if bottom is not None: raise TypeError('Cannot pass both `ymin` and `bottom`') bottom = ymin cbook.warn_deprecated('3.0', name='`ymax`', alternative='`top`', obj_type='argument') if top is not None: raise TypeError('Cannot pass both `ymax` and `top`') top = ymax
bottom = old_bottom top = old_top
warnings.warn( ('Attempting to set identical bottom==top results\n' 'in singular transformations; automatically expanding.\n' 'bottom=%s, top=%s') % (bottom, top), stacklevel=2)
if bottom <= 0: warnings.warn( 'Attempted to set non-positive bottom ylim on a ' 'log-scaled axis.\n' 'Invalid limit will be ignored.', stacklevel=2) bottom = old_bottom if top <= 0: warnings.warn( 'Attempted to set non-positive top ylim on a ' 'log-scaled axis.\n' 'Invalid limit will be ignored.', stacklevel=2) top = old_top
# Call all of the other y-axes that are shared with this one other.set_ylim(self.viewLim.intervaly, emit=False, auto=auto) if (other.figure != self.figure and other.figure.canvas is not None): other.figure.canvas.draw_idle()
""" Return the x-axis scale as string.
See Also -------- set_yscale """
""" Set the y-axis scale.
Parameters ---------- value : {"linear", "log", "symlog", "logit", ...} The axis scale type to apply.
**kwargs Different keyword arguments are accepted, depending on the scale. See the respective class keyword arguments:
- `matplotlib.scale.LinearScale` - `matplotlib.scale.LogScale` - `matplotlib.scale.SymmetricalLogScale` - `matplotlib.scale.LogitScale`
Notes ----- By default, Matplotlib supports the above mentioned scales. Additionally, custom scales may be registered using `matplotlib.scale.register_scale`. These scales can then also be used here. """ g = self.get_shared_y_axes() for ax in g.get_siblings(self): ax.yaxis._set_scale(value, **kwargs) ax._update_transScale() ax.stale = True self.autoscale_view(scalex=False)
"""Return the y ticks as a list of locations""" return self.yaxis.get_ticklocs(minor=minor)
""" Set the y ticks with list of *ticks*
Parameters ---------- ticks : list List of y-axis tick locations
minor : bool, optional If ``False`` sets major ticks, if ``True`` sets minor ticks. Default is ``False``. """
""" Get the major y tick labels.
Returns ------- labels : list List of :class:`~matplotlib.text.Text` instances """ return cbook.silent_list('Text yticklabel', self.yaxis.get_majorticklabels())
""" Get the minor y tick labels.
Returns ------- labels : list List of :class:`~matplotlib.text.Text` instances """ return cbook.silent_list('Text yticklabel', self.yaxis.get_minorticklabels())
""" Get the y tick labels as a list of :class:`~matplotlib.text.Text` instances.
Parameters ---------- minor : bool If True return the minor ticklabels, else return the major ticklabels
which : None, ('minor', 'major', 'both') Overrides `minor`.
Selects which ticklabels to return
Returns ------- ret : list List of :class:`~matplotlib.text.Text` instances. """ return cbook.silent_list('Text yticklabel', self.yaxis.get_ticklabels(minor=minor, which=which))
""" Set the y-tick labels with list of strings labels.
Parameters ---------- labels : List[str] list of string labels
fontdict : dict, optional A dictionary controlling the appearance of the ticklabels. The default `fontdict` is::
{'fontsize': rcParams['axes.titlesize'], 'fontweight': rcParams['axes.titleweight'], 'verticalalignment': 'baseline', 'horizontalalignment': loc}
minor : bool, optional Whether to set the minor ticklabels rather than the major ones.
Returns ------- A list of `~.text.Text` instances.
Other Parameters ---------------- **kwargs : `~.text.Text` properties. """ kwargs.update(fontdict) minor=minor, **kwargs)
""" Sets up x-axis ticks and labels that treat the x data as dates.
Parameters ---------- tz : string or :class:`tzinfo` instance, optional Timezone string or timezone. Defaults to rc value. """ # should be enough to inform the unit conversion interface # dates are coming in self.xaxis.axis_date(tz)
""" Sets up y-axis ticks and labels that treat the y data as dates.
Parameters ---------- tz : string or :class:`tzinfo` instance, optional Timezone string or timezone. Defaults to rc value. """ self.yaxis.axis_date(tz)
""" Return *x* string formatted. This function will use the attribute self.fmt_xdata if it is callable, else will fall back on the xaxis major formatter """ try: return self.fmt_xdata(x) except TypeError: func = self.xaxis.get_major_formatter().format_data_short val = func(x) return val
""" Return y string formatted. This function will use the :attr:`fmt_ydata` attribute if it is callable, else will fall back on the yaxis major formatter """ try: return self.fmt_ydata(y) except TypeError: func = self.yaxis.get_major_formatter().format_data_short val = func(y) return val
"""Return a format string formatting the *x*, *y* coord""" if x is None: xs = '???' else: xs = self.format_xdata(x) if y is None: ys = '???' else: ys = self.format_ydata(y) return 'x=%s y=%s' % (xs, ys)
""" Display minor ticks on the axes.
Displaying minor ticks may reduce performance; you may turn them off using `minorticks_off()` if drawing speed is a problem. """ for ax in (self.xaxis, self.yaxis): scale = ax.get_scale() if scale == 'log': s = ax._scale ax.set_minor_locator(mticker.LogLocator(s.base, s.subs)) elif scale == 'symlog': s = ax._scale ax.set_minor_locator( mticker.SymmetricalLogLocator(s._transform, s.subs)) else: ax.set_minor_locator(mticker.AutoMinorLocator())
"""Remove minor ticks from the axes.""" self.xaxis.set_minor_locator(mticker.NullLocator()) self.yaxis.set_minor_locator(mticker.NullLocator())
# Interactive manipulation
""" Return *True* if this axes supports the zoom box button functionality. """ return True
""" Return *True* if this axes supports any pan/zoom button functionality. """ return True
""" Get whether the axes responds to navigation commands """ return self._navigate
""" Set whether the axes responds to navigation toolbar commands
Parameters ---------- b : bool """
""" Get the navigation toolbar button status: 'PAN', 'ZOOM', or None """ return self._navigate_mode
""" Set the navigation toolbar button status;
.. warning:: this is not a user-API function.
"""
""" Save information required to reproduce the current view.
Called before a view is changed, such as during a pan or zoom initiated by the user. You may return any information you deem necessary to describe the view.
.. note::
Intended to be overridden by new projection types, but if not, the default implementation saves the view limits. You *must* implement :meth:`_set_view` if you implement this method. """ xmin, xmax = self.get_xlim() ymin, ymax = self.get_ylim() return (xmin, xmax, ymin, ymax)
""" Apply a previously saved view.
Called when restoring a view, such as with the navigation buttons.
.. note::
Intended to be overridden by new projection types, but if not, the default implementation restores the view limits. You *must* implement :meth:`_get_view` if you implement this method. """ xmin, xmax, ymin, ymax = view self.set_xlim((xmin, xmax)) self.set_ylim((ymin, ymax))
mode=None, twinx=False, twiny=False): """ Update view from a selection bbox.
.. note::
Intended to be overridden by new projection types, but if not, the default implementation sets the view limits to the bbox directly.
Parameters ----------
bbox : 4-tuple or 3 tuple * If bbox is a 4 tuple, it is the selected bounding box limits, in *display* coordinates. * If bbox is a 3 tuple, it is an (xp, yp, scl) triple, where (xp,yp) is the center of zooming and scl the scale factor to zoom by.
direction : str The direction to apply the bounding box. * `'in'` - The bounding box describes the view directly, i.e., it zooms in. * `'out'` - The bounding box describes the size to make the existing view, i.e., it zooms out.
mode : str or None The selection mode, whether to apply the bounding box in only the `'x'` direction, `'y'` direction or both (`None`).
twinx : bool Whether this axis is twinned in the *x*-direction.
twiny : bool Whether this axis is twinned in the *y*-direction. """ Xmin, Xmax = self.get_xlim() Ymin, Ymax = self.get_ylim()
if len(bbox) == 3: # Zooming code xp, yp, scl = bbox
# Should not happen if scl == 0: scl = 1.
# direction = 'in' if scl > 1: direction = 'in' else: direction = 'out' scl = 1/scl
# get the limits of the axes tranD2C = self.transData.transform xmin, ymin = tranD2C((Xmin, Ymin)) xmax, ymax = tranD2C((Xmax, Ymax))
# set the range xwidth = xmax - xmin ywidth = ymax - ymin xcen = (xmax + xmin)*.5 ycen = (ymax + ymin)*.5 xzc = (xp*(scl - 1) + xcen)/scl yzc = (yp*(scl - 1) + ycen)/scl
bbox = [xzc - xwidth/2./scl, yzc - ywidth/2./scl, xzc + xwidth/2./scl, yzc + ywidth/2./scl] elif len(bbox) != 4: # should be len 3 or 4 but nothing else warnings.warn( "Warning in _set_view_from_bbox: bounding box is not a tuple " "of length 3 or 4. Ignoring the view change.", stacklevel=2) return
# Just grab bounding box lastx, lasty, x, y = bbox
# zoom to rect inverse = self.transData.inverted() lastx, lasty = inverse.transform_point((lastx, lasty)) x, y = inverse.transform_point((x, y))
if twinx: x0, x1 = Xmin, Xmax else: if Xmin < Xmax: if x < lastx: x0, x1 = x, lastx else: x0, x1 = lastx, x if x0 < Xmin: x0 = Xmin if x1 > Xmax: x1 = Xmax else: if x > lastx: x0, x1 = x, lastx else: x0, x1 = lastx, x if x0 > Xmin: x0 = Xmin if x1 < Xmax: x1 = Xmax
if twiny: y0, y1 = Ymin, Ymax else: if Ymin < Ymax: if y < lasty: y0, y1 = y, lasty else: y0, y1 = lasty, y if y0 < Ymin: y0 = Ymin if y1 > Ymax: y1 = Ymax else: if y > lasty: y0, y1 = y, lasty else: y0, y1 = lasty, y if y0 > Ymin: y0 = Ymin if y1 < Ymax: y1 = Ymax
if direction == 'in': if mode == 'x': self.set_xlim((x0, x1)) elif mode == 'y': self.set_ylim((y0, y1)) else: self.set_xlim((x0, x1)) self.set_ylim((y0, y1)) elif direction == 'out': if self.get_xscale() == 'log': alpha = np.log(Xmax / Xmin) / np.log(x1 / x0) rx1 = pow(Xmin / x0, alpha) * Xmin rx2 = pow(Xmax / x0, alpha) * Xmin else: alpha = (Xmax - Xmin) / (x1 - x0) rx1 = alpha * (Xmin - x0) + Xmin rx2 = alpha * (Xmax - x0) + Xmin if self.get_yscale() == 'log': alpha = np.log(Ymax / Ymin) / np.log(y1 / y0) ry1 = pow(Ymin / y0, alpha) * Ymin ry2 = pow(Ymax / y0, alpha) * Ymin else: alpha = (Ymax - Ymin) / (y1 - y0) ry1 = alpha * (Ymin - y0) + Ymin ry2 = alpha * (Ymax - y0) + Ymin
if mode == 'x': self.set_xlim((rx1, rx2)) elif mode == 'y': self.set_ylim((ry1, ry2)) else: self.set_xlim((rx1, rx2)) self.set_ylim((ry1, ry2))
""" Called when a pan operation has started.
*x*, *y* are the mouse coordinates in display coords. button is the mouse button number:
* 1: LEFT * 2: MIDDLE * 3: RIGHT
.. note::
Intended to be overridden by new projection types.
""" self._pan_start = types.SimpleNamespace( lim=self.viewLim.frozen(), trans=self.transData.frozen(), trans_inverse=self.transData.inverted().frozen(), bbox=self.bbox.frozen(), x=x, y=y)
""" Called when a pan operation completes (when the mouse button is up.)
.. note::
Intended to be overridden by new projection types.
""" del self._pan_start
""" Called when the mouse moves during a pan operation.
*button* is the mouse button number:
* 1: LEFT * 2: MIDDLE * 3: RIGHT
*key* is a "shift" key
*x*, *y* are the mouse coordinates in display coords.
.. note::
Intended to be overridden by new projection types.
""" def format_deltas(key, dx, dy): if key == 'control': if abs(dx) > abs(dy): dy = dx else: dx = dy elif key == 'x': dy = 0 elif key == 'y': dx = 0 elif key == 'shift': if 2 * abs(dx) < abs(dy): dx = 0 elif 2 * abs(dy) < abs(dx): dy = 0 elif abs(dx) > abs(dy): dy = dy / abs(dy) * abs(dx) else: dx = dx / abs(dx) * abs(dy) return dx, dy
p = self._pan_start dx = x - p.x dy = y - p.y if dx == dy == 0: return if button == 1: dx, dy = format_deltas(key, dx, dy) result = p.bbox.translated(-dx, -dy).transformed(p.trans_inverse) elif button == 3: try: dx = -dx / self.bbox.width dy = -dy / self.bbox.height dx, dy = format_deltas(key, dx, dy) if self.get_aspect() != 'auto': dx = dy = 0.5 * (dx + dy) alpha = np.power(10.0, (dx, dy)) start = np.array([p.x, p.y]) oldpoints = p.lim.transformed(p.trans) newpoints = start + alpha * (oldpoints - start) result = (mtransforms.Bbox(newpoints) .transformed(p.trans_inverse)) except OverflowError: warnings.warn('Overflow while panning', stacklevel=2) return else: return
valid = np.isfinite(result.transformed(p.trans)) points = result.get_points().astype(object) # Just ignore invalid limits (typically, underflow in log-scale). points[~valid] = None self.set_xlim(points[:, 0]) self.set_ylim(points[:, 1])
"""return a list of child artists"""
""" Test whether the mouse event occurred in the axes.
Returns *True* / *False*, {} """ if callable(self._contains): return self._contains(self, mouseevent) return self.patch.contains(mouseevent)
""" Returns *True* if the point (tuple of x,y) is inside the axes (the area defined by the its patch). A pixel coordinate is required.
"""
"""Trigger pick event
Call signature::
pick(mouseevent)
each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set """ martist.Artist.pick(self, args[0])
""" Return a default list of artists that are used for the bounding box calculation.
Artists are excluded either by not being visible or ``artist.set_in_layout(False)``. """
artists = self.get_children() if not (self.axison and self._frameon): # don't do bbox on spines if frame not on. for spine in self.spines.values(): artists.remove(spine)
if not self.axison: for _axis in self._get_axis_list(): artists.remove(_axis)
return [artist for artist in artists if (artist.get_visible() and artist.get_in_layout())]
bbox_extra_artists=None): """ Return the tight bounding box of the axes, including axis and their decorators (xlabel, title, etc).
Artists that have ``artist.set_in_layout(False)`` are not included in the bbox.
Parameters ---------- renderer : `.RendererBase` instance renderer that will be used to draw the figures (i.e. ``fig.canvas.get_renderer()``)
bbox_extra_artists : list of `.Artist` or ``None`` List of artists to include in the tight bounding box. If ``None`` (default), then all artist children of the axes are included in the tight bounding box.
call_axes_locator : boolean (default ``True``) If *call_axes_locator* is ``False``, it does not call the ``_axes_locator`` attribute, which is necessary to get the correct bounding box. ``call_axes_locator=False`` can be used if the caller is only interested in the relative size of the tightbbox compared to the axes bbox.
Returns ------- bbox : `.BboxBase` bounding box in figure pixel coordinates. """
bb = []
if not self.get_visible(): return None
locator = self.get_axes_locator() if locator and call_axes_locator: pos = locator(self, renderer) self.apply_aspect(pos) else: self.apply_aspect()
bb_xaxis = self.xaxis.get_tightbbox(renderer) if bb_xaxis: bb.append(bb_xaxis)
self._update_title_position(renderer) bb.append(self.get_window_extent(renderer))
if self.title.get_visible(): bb.append(self.title.get_window_extent(renderer)) if self._left_title.get_visible(): bb.append(self._left_title.get_window_extent(renderer)) if self._right_title.get_visible(): bb.append(self._right_title.get_window_extent(renderer))
bb_yaxis = self.yaxis.get_tightbbox(renderer) if bb_yaxis: bb.append(bb_yaxis)
bbox_artists = bbox_extra_artists if bbox_artists is None: bbox_artists = self.get_default_bbox_extra_artists()
for a in bbox_artists: bbox = a.get_tightbbox(renderer) if (bbox is not None and (bbox.width != 0 or bbox.height != 0) and np.isfinite(bbox.width) and np.isfinite(bbox.height)): bb.append(bbox)
_bbox = mtransforms.Bbox.union( [b for b in bb if b.width != 0 or b.height != 0])
return _bbox
""" Make a twinx axes of self. This is used for twinx and twiny. """ # Typically, SubplotBase._make_twin_axes is called instead of this. # There is also an override in axes_grid1/axes_divider.py. if 'sharex' in kwargs and 'sharey' in kwargs: raise ValueError("Twinned Axes may share only one axis.") ax2 = self.figure.add_axes(self.get_position(True), *kl, **kwargs) self.set_adjustable('datalim') ax2.set_adjustable('datalim') self._twinned_axes.join(self, ax2) return ax2
""" Create a twin Axes sharing the xaxis
Create a new Axes instance with an invisible x-axis and an independent y-axis positioned opposite to the original one (i.e. at right). The x-axis autoscale setting will be inherited from the original Axes. To ensure that the tick marks of both y-axes align, see `~matplotlib.ticker.LinearLocator`
Returns ------- ax_twin : Axes The newly created Axes instance
Notes ----- For those who are 'picking' artists while using twinx, pick events are only called for the artists in the top-most axes. """
""" Create a twin Axes sharing the yaxis
Create a new Axes instance with an invisible y-axis and an independent x-axis positioned opposite to the original one (i.e. at top). The y-axis autoscale setting will be inherited from the original Axes. To ensure that the tick marks of both x-axes align, see `~matplotlib.ticker.LinearLocator`
Returns ------- ax_twin : Axes The newly created Axes instance
Notes ----- For those who are 'picking' artists while using twiny, pick events are only called for the artists in the top-most axes. """
ax2 = self._make_twin_axes(sharey=self) ax2.xaxis.tick_top() ax2.xaxis.set_label_position('top') ax2.set_autoscaley_on(self.get_autoscaley_on()) self.xaxis.tick_bottom() ax2.yaxis.set_visible(False) ax2.patch.set_visible(False) return ax2
"""Return a reference to the shared axes Grouper object for x axes.""" return self._shared_x_axes
"""Return a reference to the shared axes Grouper object for y axes.""" return self._shared_y_axes |