FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

GitHub Viewer

""" Classes for the ticks and x- and y-axis. """ import contextlib import datetime import functools import logging from numbers import Real import warnings import numpy as np import matplotlib as mpl from matplotlib import _api, cbook import matplotlib.artist as martist import matplotlib.colors as mcolors import matplotlib.lines as mlines import matplotlib.scale as mscale import matplotlib.text as mtext import matplotlib.ticker as mticker import matplotlib.transforms as mtransforms import matplotlib.units as munits from matplotlib.ticker import NullLocator _log = logging.getLogger(__name__) GRIDLINE_INTERPOLATION_STEPS = 180 # This list is being used for compatibility with Axes.grid, which # allows all Line2D kwargs. _line_inspector = martist.ArtistInspector(mlines.Line2D) _line_param_names = _line_inspector.get_setters() _line_param_aliases = [next(iter(d)) for d in _line_inspector.aliasd.values()] _gridline_param_names = ['grid_' + name for name in _line_param_names + _line_param_aliases] class Tick(martist.Artist): """ Abstract base class for the axis ticks, grid lines and labels. Ticks mark a position on an Axis. They contain two lines as markers and two labels; one each for the bottom and top positions (in case of an `.XAxis`) or for the left and right positions (in case of a `.YAxis`). Attributes ---------- tick1line : `~matplotlib.lines.Line2D` The left/bottom tick marker. tick2line : `~matplotlib.lines.Line2D` The right/top tick marker. gridline : `~matplotlib.lines.Line2D` The grid line associated with the label position. label1 : `~matplotlib.text.Text` The left/bottom tick label. label2 : `~matplotlib.text.Text` The right/top tick label. Notes ----- Ticks are managed though the autoscaling / view limit mechanism and therefore need very careful handling when explicitly accessed, see :ref:`axes-tick-objects`. The tick lines are implemented as `~matplotlib.lines.Line2D` instances using the `~.matplotlib.markers` TICKLEFT, TICKRIGHT, TICKDOWN, TICKUP. Therefore, properties are controlled via the marker, e.g. for the color `.Line2D.set_markeredgecolor` and not `.Line2D.set_color`. """ def __init__( self, axes, loc, *, size=None, # points width=None, color=None, tickdir=None, pad=None, labelsize=None, labelcolor=None, labelfontfamily=None, zorder=None, gridOn=None, # defaults to axes.grid depending on axes.grid.which tick1On=True, tick2On=True, label1On=True, label2On=False, major=True, labelrotation=0, labelrotation_mode=None, grid_color=None, grid_linestyle=None, grid_linewidth=None, grid_alpha=None, **kwargs, # Other Line2D kwargs applied to gridlines. ): """ Parameters ---------- loc The tick location in data coords. size The tick size in points. """ super().__init__() if gridOn is None: which = mpl.rcParams['axes.grid.which'] if major and which in ('both', 'major'): gridOn = mpl.rcParams['axes.grid'] elif not major and which in ('both', 'minor'): gridOn = mpl.rcParams['axes.grid'] else: gridOn = False self.set_figure(axes.get_figure(root=False)) self.axes = axes self._loc = loc self._major = major name = self.__name__ major_minor = "major" if major else "minor" self._size = mpl._val_or_rc(size, f"{name}.{major_minor}.size") self._width = mpl._val_or_rc(width, f"{name}.{major_minor}.width") self._base_pad = mpl._val_or_rc(pad, f"{name}.{major_minor}.pad") color = mpl._val_or_rc(color, f"{name}.color") labelcolor = mpl._val_or_rc(labelcolor, f"{name}.labelcolor") if cbook._str_equal(labelcolor, 'inherit'): # inherit from tick color labelcolor = mpl.rcParams[f"{name}.color"] labelsize = mpl._val_or_rc(labelsize, f"{name}.labelsize") self._set_labelrotation(labelrotation) if zorder is None: if major: zorder = mlines.Line2D.zorder + 0.01 else: zorder = mlines.Line2D.zorder self._zorder = zorder grid_color = mpl._val_or_rc( grid_color, f"grid.{major_minor}.color", "grid.color", ) grid_linestyle = mpl._val_or_rc( grid_linestyle, f"grid.{major_minor}.linestyle", "grid.linestyle", ) grid_linewidth = mpl._val_or_rc( grid_linewidth, f"grid.{major_minor}.linewidth", "grid.linewidth", ) if grid_alpha is None: if mcolors._has_alpha_channel(grid_color): # Extract alpha from the color # alpha precedence: kwarg > color alpha > rcParams['grid.alpha'] rgba = mcolors.to_rgba(grid_color) grid_color = rgba[:3] # RGB only grid_alpha = rgba[3] # Alpha from color else: # No alpha in color, use rcParams grid_alpha = mpl._val_or_rc( # grid_alpha is None so we can use the first key mpl.rcParams[f"grid.{major_minor}.alpha"], "grid.alpha", ) grid_kw = {k[5:]: v for k, v in kwargs.items() if k != "rotation_mode"} self.tick1line = mlines.Line2D( [], [], color=color, linestyle="none", zorder=zorder, visible=tick1On, markeredgecolor=color, markersize=self._size, markeredgewidth=self._width, ) self.tick2line = mlines.Line2D( [], [], color=color, linestyle="none", zorder=zorder, visible=tick2On, markeredgecolor=color, markersize=self._size, markeredgewidth=self._width, ) self.gridline = mlines.Line2D( [], [], color=grid_color, alpha=grid_alpha, visible=gridOn, linestyle=grid_linestyle, linewidth=grid_linewidth, marker="", **grid_kw, ) self.gridline.get_path()._interpolation_steps = \ GRIDLINE_INTERPOLATION_STEPS self.label1 = mtext.Text( np.nan, np.nan, fontsize=labelsize, color=labelcolor, visible=label1On, fontfamily=labelfontfamily, rotation=self._labelrotation[1], rotation_mode=labelrotation_mode) self.label2 = mtext.Text( np.nan, np.nan, fontsize=labelsize, color=labelcolor, visible=label2On, fontfamily=labelfontfamily, rotation=self._labelrotation[1], rotation_mode=labelrotation_mode) self._apply_tickdir(tickdir) for artist in [self.tick1line, self.tick2line, self.gridline, self.label1, self.label2]: self._set_artist_props(artist) self.update_position(loc) def _set_labelrotation(self, labelrotation): if isinstance(labelrotation, str): mode = labelrotation angle = 0 elif isinstance(labelrotation, (tuple, list)): mode, angle = labelrotation else: mode = 'default' angle = labelrotation _api.check_in_list(['auto', 'default'], labelrotation=mode) self._labelrotation = (mode, angle) @property def _pad(self): return self._base_pad + self.get_tick_padding() def _apply_tickdir(self, tickdir): """Set tick direction. Valid values are 'out', 'in', 'inout'.""" # This method is responsible for verifying input and, in subclasses, for setting # the tick{1,2}line markers. From the user perspective this should always be # called through _apply_params, which further updates ticklabel positions using # the new pads. tickdir = mpl._val_or_rc(tickdir, f'{self.__name__}.direction') _api.check_in_list(['in', 'out', 'inout'], tickdir=tickdir) self._tickdir = tickdir def get_tickdir(self): return self._tickdir def get_tick_padding(self): """Get the length of the tick outside of the Axes.""" padding = { 'in': 0.0, 'inout': 0.5, 'out': 1.0 } return self._size * padding[self._tickdir] def get_children(self): children = [self.tick1line, self.tick2line, self.gridline, self.label1, self.label2] return children def set_clip_path(self, path, transform=None): # docstring inherited super().set_clip_path(path, transform) self.gridline.set_clip_path(path, transform) self.stale = True def _configure_for_axis(self, axis, major): """ Apply axis-level configuration to a freshly-materialized Tick. Used by `_LazyTickList` to apply ``set_tick_params()`` overrides held on the Axis and to stamp the clip state set via ``Axis.set_clip_path`` onto the Tick and its gridline. """ # Subclasses of Axis (e.g. SkewXAxis in the skewt gallery example) # may override _get_tick() without forwarding _{major,minor}_tick_kw, # so apply them here. tick_kw = axis._major_tick_kw if major else axis._minor_tick_kw if tick_kw: self._apply_params(**tick_kw) for artist in (self, self.gridline): artist.clipbox = axis.clipbox artist._clippath = axis._clippath artist._clipon = axis._clipon def contains(self, mouseevent): """ Test whether the mouse event occurred in the Tick marks. This function always returns false. It is more useful to test if the axis as a whole contains the mouse rather than the set of tick marks. """ return False, {} def set_pad(self, val): """ Set the tick label pad in points Parameters ---------- val : float """ self._apply_params(pad=val) self.stale = True def get_pad(self): """Get the value of the tick label pad in points.""" return self._base_pad def get_loc(self): """Return the tick location (data coords) as a scalar.""" return self._loc @martist.allow_rasterization def draw(self, renderer): if not self.get_visible(): self.stale = False return renderer.open_group(self.__name__, gid=self.get_gid()) for artist in [self.gridline, self.tick1line, self.tick2line, self.label1, self.label2]: artist.draw(renderer) renderer.close_group(self.__name__) self.stale = False def set_url(self, url): """ Set the url of label1 and label2. Parameters ---------- url : str """ super().set_url(url) self.label1.set_url(url) self.label2.set_url(url) self.stale = True def _set_artist_props(self, a): a.set_figure(self.get_figure(root=False)) def get_view_interval(self): """ Return the view limits ``(min, max)`` of the axis the tick belongs to. """ raise NotImplementedError('Derived must override') def _apply_params(self, **kwargs): for name, target in [("gridOn", self.gridline), ("tick1On", self.tick1line), ("tick2On", self.tick2line), ("label1On", self.label1), ("label2On", self.label2)]: if name in kwargs: target.set_visible(kwargs.pop(name)) if any(k in kwargs for k in ['size', 'width', 'pad', 'tickdir']): self._size = kwargs.pop('size', self._size) # Width could be handled outside this block, but it is # convenient to leave it here. self._width = kwargs.pop('width', self._width) self._base_pad = kwargs.pop('pad', self._base_pad) # _apply_tickdir uses _size and _base_pad to make _pad, and also # sets the ticklines markers. self._apply_tickdir(kwargs.pop('tickdir', self._tickdir)) for line in (self.tick1line, self.tick2line): line.set_markersize(self._size) line.set_markeredgewidth(self._width) # _get_text1_transform uses _pad from _apply_tickdir. trans = self._get_text1_transform()[0] self.label1.set_transform(trans) trans = self._get_text2_transform()[0] self.label2.set_transform(trans) tick_kw = {k: v for k, v in kwargs.items() if k in ['color', 'zorder']} if 'color' in kwargs: tick_kw['markeredgecolor'] = kwargs['color'] self.tick1line.set(**tick_kw) self.tick2line.set(**tick_kw) for k, v in tick_kw.items(): setattr(self, '_' + k, v) if 'labelrotation' in kwargs: self._set_labelrotation(kwargs.pop('labelrotation')) self.label1.set(rotation=self._labelrotation[1]) self.label2.set(rotation=self._labelrotation[1]) label_kw = {k[5:]: v for k, v in kwargs.items() if k in ['labelsize', 'labelcolor', 'labelfontfamily', 'labelrotation_mode']} self.label1.set(**label_kw) self.label2.set(**label_kw) grid_kw = {k[5:]: v for k, v in kwargs.items() if k in _gridline_param_names} # If grid_color has an alpha channel and grid_alpha is not explicitly # set, extract the alpha from the color. if 'color' in grid_kw and 'alpha' not in grid_kw: grid_color = grid_kw['color'] if mcolors._has_alpha_channel(grid_color): # Convert to rgba to extract alpha rgba = mcolors.to_rgba(grid_color) grid_kw['color'] = rgba[:3] # RGB only grid_kw['alpha'] = rgba[3] # Alpha channel self.gridline.set(**grid_kw) def update_position(self, loc): """Set the location of tick in data coords with scalar *loc*.""" raise NotImplementedError('Derived must override') def _get_text1_transform(self): raise NotImplementedError('Derived must override') def _get_text2_transform(self): raise NotImplementedError('Derived must override') class XTick(Tick): """ Contains all the Artists needed to make an x tick - the tick line, the label text and the grid line """ __name__ = 'xtick' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # x in data coords, y in axes coords ax = self.axes self.tick1line.set( data=([0], [0]), transform=ax.get_xaxis_transform("tick1")) self.tick2line.set( data=([0], [1]), transform=ax.get_xaxis_transform("tick2")) self.gridline.set( data=([0, 0], [0, 1]), transform=ax.get_xaxis_transform("grid")) # the y loc is 3 points below the min of y axis trans, va, ha = self._get_text1_transform() self.label1.set( x=0, y=0, verticalalignment=va, horizontalalignment=ha, transform=trans, ) trans, va, ha = self._get_text2_transform() self.label2.set( x=0, y=1, verticalalignment=va, horizontalalignment=ha, transform=trans, ) def _get_text1_transform(self): return self.axes.get_xaxis_text1_transform(self._pad) def _get_text2_transform(self): return self.axes.get_xaxis_text2_transform(self._pad) def _apply_tickdir(self, tickdir): # docstring inherited super()._apply_tickdir(tickdir) mark1, mark2 = { 'out': (mlines.TICKDOWN, mlines.TICKUP), 'in': (mlines.TICKUP, mlines.TICKDOWN), 'inout': ('|', '|'), }[self._tickdir] self.tick1line.set_marker(mark1) self.tick2line.set_marker(mark2) def update_position(self, loc): """Set the location of tick in data coords with scalar *loc*.""" self.tick1line.set_xdata((loc,)) self.tick2line.set_xdata((loc,)) self.gridline.set_xdata((loc,)) self.label1.set_x(loc) self.label2.set_x(loc) self._loc = loc self.stale = True def get_view_interval(self): # docstring inherited return self.axes.viewLim.intervalx class YTick(Tick): """ Contains all the Artists needed to make a Y tick - the tick line, the label text and the grid line """ __name__ = 'ytick' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # x in axes coords, y in data coords ax = self.axes self.tick1line.set( data=([0], [0]), transform=ax.get_yaxis_transform("tick1")) self.tick2line.set( data=([1], [0]), transform=ax.get_yaxis_transform("tick2")) self.gridline.set( data=([0, 1], [0, 0]), transform=ax.get_yaxis_transform("grid")) # the y loc is 3 points below the min of y axis trans, va, ha = self._get_text1_transform() self.label1.set( x=0, y=0, verticalalignment=va, horizontalalignment=ha, transform=trans, ) trans, va, ha = self._get_text2_transform() self.label2.set( x=1, y=0, verticalalignment=va, horizontalalignment=ha, transform=trans, ) def _get_text1_transform(self): return self.axes.get_yaxis_text1_transform(self._pad) def _get_text2_transform(self): return self.axes.get_yaxis_text2_transform(self._pad) def _apply_tickdir(self, tickdir): # docstring inherited super()._apply_tickdir(tickdir) mark1, mark2 = { 'out': (mlines.TICKLEFT, mlines.TICKRIGHT), 'in': (mlines.TICKRIGHT, mlines.TICKLEFT), 'inout': ('_', '_'), }[self._tickdir] self.tick1line.set_marker(mark1) self.tick2line.set_marker(mark2) def update_position(self, loc): """Set the location of tick in data coords with scalar *loc*.""" self.tick1line.set_ydata((loc,)) self.tick2line.set_ydata((loc,)) self.gridline.set_ydata((loc,)) self.label1.set_y(loc) self.label2.set_y(loc) self._loc = loc self.stale = True def get_view_interval(self): # docstring inherited return self.axes.viewLim.intervaly class Ticker: """ A container for the objects defining tick position and format. Attributes ---------- locator : `~matplotlib.ticker.Locator` subclass Determines the positions of the ticks. formatter : `~matplotlib.ticker.Formatter` subclass Determines the format of the tick labels. """ def __init__(self): self._locator = None self._formatter = None self._locator_is_default = True self._formatter_is_default = True @property def locator(self): return self._locator @locator.setter def locator(self, locator): if not isinstance(locator, mticker.Locator): raise TypeError('locator must be a subclass of ' 'matplotlib.ticker.Locator') self._locator = locator @property def formatter(self): return self._formatter @formatter.setter def formatter(self, formatter): if not isinstance(formatter, mticker.Formatter): raise TypeError('formatter must be a subclass of ' 'matplotlib.ticker.Formatter') self._formatter = formatter @contextlib.contextmanager def _rc_context_raw(snapshot): """ Like ``mpl.rc_context(snapshot)`` but bypasses ``RcParams`` validators on entry and exit; re-applying a snapshot to its own values must not re-trigger one-shot validator warnings (e.g. ``toolbar='toolmanager'``). ``snapshot=None`` is a no-op. """ if snapshot is None: yield return rc = mpl.rcParams orig = dict(rc) rc._update_raw(snapshot) try: yield finally: rc._update_raw(orig) class _LazyTickList: """ A descriptor for lazy instantiation of tick lists. See comment above definition of the ``majorTicks`` and ``minorTicks`` attributes. """ def __init__(self, major): self._major = major def __get__(self, instance, owner): """Materialize the descriptor to a list with one configured tick.""" if instance is None: return self # 1. Bind a placeholder so reentrant access via _get_tick() (e.g. # projections overriding get_xaxis_text1_transform) does not # recurse back into this descriptor. # 2. Build the tick under the rcParams snapshot from the last # Axis.clear() so its sub-artists pick up the right rcParams. # 3. Apply set_tick_params() overrides and axis state. # 4. Re-bind the final list; _get_tick() may have called # reset_ticks(), which pops the attribute, so this assignment # is what makes future accesses skip the descriptor. attr = 'majorTicks' if self._major else 'minorTicks' setattr(instance, attr, ()) # placeholder; not appended to with _rc_context_raw(instance._tick_rcParams): tick = instance._get_tick(major=self._major) tick._configure_for_axis(instance, self._major) tick_list = [tick] setattr(instance, attr, tick_list) return tick_list class Axis(martist.Artist): """ Base class for `.XAxis` and `.YAxis`. Attributes ---------- isDefault_label : bool axes : `~matplotlib.axes.Axes` The `~.axes.Axes` to which the Axis belongs. major : `~matplotlib.axis.Ticker` Determines the major tick positions and their label format. minor : `~matplotlib.axis.Ticker` Determines the minor tick positions and their label format. callbacks : `~matplotlib.cbook.CallbackRegistry` label : `~matplotlib.text.Text` The axis label. labelpad : float The distance between the axis label and the tick labels. Defaults to :rc:`axes.labelpad`. offsetText : `~matplotlib.text.Text` A `.Text` object containing the data offset of the ticks (if any). pickradius : float The acceptance radius for containment tests. See also `.Axis.contains`. majorTicks : list of `.Tick` The major ticks. .. warning:: Ticks are not guaranteed to be persistent. Various operations can create, delete and modify the Tick instances. There is an imminent risk that changes to individual ticks will not survive if you work on the figure further (including also panning/zooming on a displayed figure). Working on the individual ticks is a method of last resort. Use `.set_tick_params` instead if possible. minorTicks : list of `.Tick` The minor ticks. """ OFFSETTEXTPAD = 3 # The class used in _get_tick() to create tick instances. Must either be # overwritten in subclasses, or subclasses must reimplement _get_tick(). _tick_class = None converter = _api.deprecate_privatize_attribute( "3.10", alternative="get_converter and set_converter methods" ) def __str__(self): return "{}({},{})".format( type(self).__name__, *self.axes.transAxes.transform((0, 0))) def __init__(self, axes, *, pickradius=15, clear=True): """ Parameters ---------- axes : `~matplotlib.axes.Axes` The `~.axes.Axes` to which the created Axis belongs. pickradius : float The acceptance radius for containment tests. See also `.Axis.contains`. clear : bool, default: True Whether to clear the Axis on creation. This is not required, e.g., when creating an Axis as part of an Axes, as ``Axes.clear`` will call ``Axis.clear``. .. versionadded:: 3.8 """ super().__init__() self._remove_overlapping_locs = True self.set_figure(axes.get_figure(root=False)) self.isDefault_label = True self.axes = axes self.major = Ticker() self.minor = Ticker() self.callbacks = cbook.CallbackRegistry(signals=["units"]) self._autolabelpos = True self.label = mtext.Text( np.nan, np.nan, fontsize=mpl.rcParams['axes.labelsize'], fontweight=mpl.rcParams['axes.labelweight'], color=mpl.rcParams['axes.labelcolor'], ) #: The `.Text` object of the axis label. self._set_artist_props(self.label) self.offsetText = mtext.Text(np.nan, np.nan) self._set_artist_props(self.offsetText) self.labelpad = mpl.rcParams['axes.labelpad'] self.pickradius = pickradius # Initialize here for testing; later add API self._major_tick_kw = dict() self._minor_tick_kw = dict() # Snapshot of rcParams from the last Axis.clear() (or # set_tick_params(reset=True)); re-applied by _LazyTickList when # it lazily materializes a Tick. Kept separate from # _major_tick_kw/_minor_tick_kw, which hold user-provided # set_tick_params() overrides rather than ambient rcParams. self._tick_rcParams = None if clear: self.clear() else: self._converter = None self._converter_is_explicit = False self.units = None self._autoscale_on = True @property def isDefault_majloc(self): return self.major._locator_is_default @isDefault_majloc.setter def isDefault_majloc(self, value): self.major._locator_is_default = value @property def isDefault_majfmt(self): return self.major._formatter_is_default @isDefault_majfmt.setter def isDefault_majfmt(self, value): self.major._formatter_is_default = value @property def isDefault_minloc(self): return self.minor._locator_is_default @isDefault_minloc.setter def isDefault_minloc(self, value): self.minor._locator_is_default = value @property def isDefault_minfmt(self): return self.minor._formatter_is_default @isDefault_minfmt.setter def isDefault_minfmt(self, value): self.minor._formatter_is_default = value def _get_shared_axes(self): """Return a list of shared Axes for current axis.""" return self.axes._shared_axes[ self._get_axis_name()].get_siblings(self.axes) def _get_shared_axis(self): """Return list of shared axis for current axis.""" name = self._get_axis_name() return [ax._axis_map[name] for ax in self._get_shared_axes()] def _get_axis_name(self): """Return the axis name.""" return next(name for name, axis in self.axes._axis_map.items() if axis is self) # During initialization, Axis objects often create ticks that are later # unused; this turns out to be a very slow step. Instead, use a custom # descriptor to make the tick lists lazy and instantiate them as needed. majorTicks = _LazyTickList(major=True) minorTicks = _LazyTickList(major=False) def get_remove_overlapping_locs(self): return self._remove_overlapping_locs def set_remove_overlapping_locs(self, val): self._remove_overlapping_locs = bool(val) remove_overlapping_locs = property( get_remove_overlapping_locs, set_remove_overlapping_locs, doc=('If minor ticker locations that overlap with major ' 'ticker locations should be trimmed.')) def set_label_coords(self, x, y, transform=None): """ Set the coordinates of the label. By default, the x coordinate of the y label and the y coordinate of the x label are determined by the tick label bounding boxes, but this can lead to poor alignment of multiple labels if there are multiple Axes. You can also specify the coordinate system of the label with the transform. If None, the default coordinate system will be the axes coordinate system: (0, 0) is bottom left, (0.5, 0.5) is center, etc. """ self._autolabelpos = False if transform is None: transform = self.axes.transAxes self.label.set_transform(transform) self.label.set_position((x, y)) self.stale = True def get_transform(self): """Return the transform used in the Axis' scale""" return self._scale.get_transform() def get_scale(self): """Return this Axis' scale (as a str).""" return self._scale.name def _set_scale(self, value, **kwargs): if not isinstance(value, mscale.ScaleBase): self._scale = mscale.scale_factory(value, self, **kwargs) else: self._scale = value self._scale.set_default_locators_and_formatters(self) self.isDefault_majloc = True self.isDefault_minloc = True self.isDefault_majfmt = True self.isDefault_minfmt = True # This method is directly wrapped by Axes.set_{x,y}scale. def _set_axes_scale(self, value, **kwargs): """ Set this Axis' scale. Parameters ---------- value : str or `.ScaleBase` The axis scale type to apply. Valid string values are the names of scale classes ("linear", "log", "function",...). These may be the names of any of the :ref:`built-in scales` or of any custom scales registered using `matplotlib.scale.register_scale`. **kwargs If *value* is a string, keywords are passed to the instantiation method of the respective class. """ name = self._get_axis_name() old_default_lims = (self.get_major_locator() .nonsingular(-np.inf, np.inf)) for ax in self._get_shared_axes(): ax._axis_map[name]._set_scale(value, **kwargs) ax._update_transScale() ax.stale = True new_default_lims = (self.get_major_locator() .nonsingular(-np.inf, np.inf)) if old_default_lims != new_default_lims: # Force autoscaling now, to take advantage of the scale locator's # nonsingular() before it possibly gets swapped out by the user. self.axes.autoscale_view( **{f"scale{k}": k == name for k in self.axes._axis_names}) def limit_range_for_scale(self, vmin, vmax): """ Return the range *vmin*, *vmax*, restricted to the domain supported by the current scale. """ return self._scale.limit_range_for_scale(vmin, vmax, self.get_minpos()) def _nan_out_of_scale_range(self, data): """ Return *data* with values that are out of range for this axis's scale replaced by NaN. E.g. `` Axis.reset_ticks -> Axis.set_clip_path -> _LazyTickList.__get__ -> Tick.__init__ -> Spine.set_position`` cascade. Reading the instance ``__dict__`` directly bypasses the descriptor. Parameters ---------- major : bool, optional If True, yield only major ticks; if False, only minor ticks; if None (default), yield major followed by minor. """ if major is None or major: yield from self.__dict__.get('majorTicks', ()) if major is None or not major: yield from self.__dict__.get('minorTicks', ()) def minorticks_on(self): """ Display default minor ticks on the Axis, depending on the scale (`~.axis.Axis.get_scale`). Scales use specific minor locators: - log: `~.LogLocator` - symlog: `~.SymmetricalLogLocator` - asinh: `~.AsinhLocator` - logit: `~.LogitLocator` - default: `~.AutoMinorLocator` Displaying minor ticks may reduce performance; you may turn them off using `minorticks_off()` if drawing speed is a problem. """ scale = self.get_scale() if scale == 'log': s = self._scale self.set_minor_locator(mticker.LogLocator(s.base, s.subs)) elif scale == 'symlog': s = self._scale self.set_minor_locator( mticker.SymmetricalLogLocator(s._transform, s.subs)) elif scale == 'asinh': s = self._scale self.set_minor_locator( mticker.AsinhLocator(s.linear_width, base=s._base, subs=s._subs)) elif scale == 'logit': self.set_minor_locator(mticker.LogitLocator(minor=True)) else: self.set_minor_locator(mticker.AutoMinorLocator()) def minorticks_off(self): """Remove minor ticks from the Axis.""" self.set_minor_locator(mticker.NullLocator()) def set_tick_params(self, which='major', reset=False, **kwargs): """ Set appearance parameters for ticks, ticklabels, and gridlines. For documentation of keyword arguments, see :meth:`matplotlib.axes.Axes.tick_params`. See Also -------- .Axis.get_tick_params View the current style settings for ticks, ticklabels, and gridlines. """ _api.check_in_list(['major', 'minor', 'both'], which=which) kwtrans = self._translate_tick_params(kwargs) # the kwargs are stored in self._major/minor_tick_kw so that any # future new ticks will automatically get them if reset: if which in ['major', 'both']: self._reset_major_tick_kw() self._major_tick_kw.update(kwtrans) if which in ['minor', 'both']: self._reset_minor_tick_kw() self._minor_tick_kw.update(kwtrans) self.reset_ticks() else: if which in ['major', 'both']: self._major_tick_kw.update(kwtrans) for tick in self._existing_ticks(major=True): tick._apply_params(**kwtrans) if which in ['minor', 'both']: self._minor_tick_kw.update(kwtrans) for tick in self._existing_ticks(major=False): tick._apply_params(**kwtrans) # labelOn and labelcolor also apply to the offset text. if 'label1On' in kwtrans or 'label2On' in kwtrans: self.offsetText.set_visible( self._major_tick_kw.get('label1On', False) or self._major_tick_kw.get('label2On', False)) if 'labelcolor' in kwtrans: self.offsetText.set_color(kwtrans['labelcolor']) self.stale = True def get_tick_params(self, which='major'): """ Get appearance parameters for ticks, ticklabels, and gridlines. .. versionadded:: 3.7 Parameters ---------- which : {'major', 'minor'}, default: 'major' The group of ticks for which the parameters are retrieved. Returns ------- dict Properties for styling tick elements added to the axis. Notes ----- This method returns the appearance parameters for styling *new* elements added to this axis and may be different from the values on current elements if they were modified directly by the user (e.g., via ``set_*`` methods on individual tick objects). Examples -------- :: >>> ax.yaxis.set_tick_params(labelsize=30, labelcolor='red', ... direction='out', which='major') >>> ax.yaxis.get_tick_params(which='major') {'direction': 'out', 'left': True, 'right': False, 'labelleft': True, 'labelright': False, 'gridOn': False, 'labelsize': 30, 'labelcolor': 'red'} >>> ax.yaxis.get_tick_params(which='minor') {'left': True, 'right': False, 'labelleft': True, 'labelright': False, 'gridOn': False} """ _api.check_in_list(['major', 'minor'], which=which) if which == 'major': return self._translate_tick_params( self._major_tick_kw, reverse=True ) return self._translate_tick_params(self._minor_tick_kw, reverse=True) @classmethod def _translate_tick_params(cls, kw, reverse=False): """ Translate the kwargs supported by `.Axis.set_tick_params` to kwargs supported by `.Tick._apply_params`. In particular, this maps axis specific names like 'top', 'left' to the generic tick1, tick2 logic of the axis. Additionally, there are some other name translations. Returns a new dict of translated kwargs. Note: Use reverse=True to translate from those supported by `.Tick._apply_params` back to those supported by `.Axis.set_tick_params`. """ kw_ = {**kw} # The following lists may be moved to a more accessible location. allowed_keys = [ 'size', 'width', 'color', 'tickdir', 'pad', 'labelsize', 'labelcolor', 'labelfontfamily', 'zorder', 'gridOn', 'tick1On', 'tick2On', 'label1On', 'label2On', 'length', 'direction', 'left', 'bottom', 'right', 'top', 'labelleft', 'labelbottom', 'labelright', 'labeltop', 'labelrotation', 'labelrotation_mode', *_gridline_param_names] keymap = { # tick_params key -> axis key 'length': 'size', 'direction': 'tickdir', 'rotation': 'labelrotation', 'rotation_mode': 'labelrotation_mode', 'left': 'tick1On', 'bottom': 'tick1On', 'right': 'tick2On', 'top': 'tick2On', 'labelleft': 'label1On', 'labelbottom': 'label1On', 'labelright': 'label2On', 'labeltop': 'label2On', } if reverse: kwtrans = {} is_x_axis = cls.axis_name == 'x' y_axis_keys = ['left', 'right', 'labelleft', 'labelright'] for oldkey, newkey in keymap.items(): if newkey in kw_: if is_x_axis and oldkey in y_axis_keys: continue else: kwtrans[oldkey] = kw_.pop(newkey) else: kwtrans = { newkey: kw_.pop(oldkey) for oldkey, newkey in keymap.items() if oldkey in kw_ } if 'colors' in kw_: c = kw_.pop('colors') kwtrans['color'] = c kwtrans['labelcolor'] = c # Maybe move the checking up to the caller of this method. for key in kw_: if key not in allowed_keys: raise ValueError( "keyword %s is not recognized; valid keywords are %s" % (key, allowed_keys)) kwtrans.update(kw_) return kwtrans def set_clip_path(self, path, transform=None): super().set_clip_path(path, transform) for child in self._existing_ticks(): child.set_clip_path(path, transform) self.stale = True def get_view_interval(self): """Return the ``(min, max)`` view limits of this axis.""" raise NotImplementedError('Derived must override') def set_view_interval(self, vmin, vmax, ignore=False): """ Set the axis view limits. This method is for internal use; Matplotlib users should typically use e.g. `~.Axes.set_xlim` or `~.Axes.set_ylim`. If *ignore* is False (the default), this method will never reduce the preexisting view limits, only expand them if *vmin* or *vmax* are not within them. Moreover, the order of *vmin* and *vmax* does not matter; the orientation of the axis will not change. If *ignore* is True, the view limits will be set exactly to ``(vmin, vmax)`` in that order. """ raise NotImplementedError('Derived must override') def get_data_interval(self): """Return the ``(min, max)`` data limits of this axis.""" raise NotImplementedError('Derived must override') def set_data_interval(self, vmin, vmax, ignore=False): """ Set the axis data limits. This method is for internal use. If *ignore* is False (the default), this method will never reduce the preexisting data limits, only expand them if *vmin* or *vmax* are not within them. Moreover, the order of *vmin* and *vmax* does not matter; the orientation of the axis will not change. If *ignore* is True, the data limits will be set exactly to ``(vmin, vmax)`` in that order. """ raise NotImplementedError('Derived must override') def get_inverted(self): """ Return whether this Axis is oriented in the "inverse" direction. The "normal" direction is increasing to the right for the x-axis and to the top for the y-axis; the "inverse" direction is increasing to the left for the x-axis and to the bottom for the y-axis. """ low, high = self.get_view_interval() return high < low def set_inverted(self, inverted): """ Set whether this Axis is oriented in the "inverse" direction. The "normal" direction is increasing to the right for the x-axis and to the top for the y-axis; the "inverse" direction is increasing to the left for the x-axis and to the bottom for the y-axis. """ a, b = self.get_view_interval() # cast to bool to avoid bad interaction between python 3.8 and np.bool_ self._set_lim(*sorted((a, b), reverse=bool(inverted)), auto=None) def set_default_intervals(self): """ Set the default limits for the axis data and view interval if they have not been not mutated yet. """ # this is mainly in support of custom object plotting. For # example, if someone passes in a datetime object, we do not # know automagically how to set the default min/max of the # data and view limits. The unit conversion AxisInfo # interface provides a hook for custom types to register # default limits through the AxisInfo.default_limits # attribute, and the derived code below will check for that # and use it if it's available (else just use 0..1) def _set_lim(self, v0, v1, *, emit=True, auto): """ Set view limits. This method is a helper for the Axes ``set_xlim``, ``set_ylim``, and ``set_zlim`` methods. Parameters ---------- v0, v1 : float The view limits. (Passing *v0* as a (low, high) pair is not supported; normalization must occur in the Axes setters.) emit : bool, default: True Whether to notify observers of limit change. auto : bool or None, default: False Whether to turn on autoscaling of the x-axis. True turns on, False turns off, None leaves unchanged. """ name = self._get_axis_name() self.axes._process_unit_info([(name, (v0, v1))], convert=False) v0 = self.axes._validate_converted_limits(v0, self.convert_units) v1 = self.axes._validate_converted_limits(v1, self.convert_units) if v0 is None or v1 is None: # Axes init calls set_xlim(0, 1) before get_xlim() can be called, # so only grab the limits if we really need them. old0, old1 = self.get_view_interval() if v0 is None: v0 = old0 if v1 is None: v1 = old1 if self.get_scale() == 'log' and (v0

Back | FazBrowse Home | New Git URL