title
stringclasses 1
value | text
stringlengths 46
1.11M
| id
stringlengths 27
30
|
|---|---|---|
lib/matplotlib/axes/_base.py/_AxesBase/add_table
class _AxesBase: def add_table(self, tab):
"""
Add a `.Table` to the Axes; return the table.
"""
_api.check_isinstance(mtable.Table, tab=tab)
self._set_artist_props(tab)
self._children.append(tab)
tab.set_clip_path(self.patch)
tab._remove_method = self._children.remove
return tab
|
negative_train_query273_06599
|
|
lib/matplotlib/axes/_base.py/_AxesBase/add_container
class _AxesBase: def add_container(self, container):
"""
Add a `.Container` to the Axes' containers; return the container.
"""
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
|
negative_train_query273_06600
|
|
lib/matplotlib/axes/_base.py/_AxesBase/_unit_change_handler
class _AxesBase: def _unit_change_handler(self, axis_name, event=None):
"""
Process axis units changes: requests updates to data and view limits.
"""
if event is None: # Allow connecting `self._unit_change_handler(name)`
return functools.partial(
self._unit_change_handler, axis_name, event=object())
_api.check_in_list(self._axis_map, axis_name=axis_name)
for line in self.lines:
line.recache_always()
self.relim()
self._request_autoscale_view(axis_name)
|
negative_train_query273_06601
|
|
lib/matplotlib/axes/_base.py/_AxesBase/relim
class _AxesBase: def relim(self, visible_only=False):
"""
Recompute the data limits based on current artists.
At present, `.Collection` instances are not supported.
Parameters
----------
visible_only : bool, default: False
Whether to exclude invisible artists.
"""
# 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 artist in self._children:
if not visible_only or artist.get_visible():
if isinstance(artist, mlines.Line2D):
self._update_line_limits(artist)
elif isinstance(artist, mpatches.Patch):
self._update_patch_limits(artist)
elif isinstance(artist, mimage.AxesImage):
self._update_image_limits(artist)
|
negative_train_query273_06602
|
|
lib/matplotlib/axes/_base.py/_AxesBase/update_datalim
class _AxesBase: def update_datalim(self, xys, updatex=True, updatey=True):
"""
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 (N, 2) array.
updatex, updatey : bool, default: True
Whether to update the x/y limits.
"""
xys = np.asarray(xys)
if not np.any(np.isfinite(xys)):
return
self.dataLim.update_from_data_xy(xys, self.ignore_existing_data_limits,
updatex=updatex, updatey=updatey)
self.ignore_existing_data_limits = False
|
negative_train_query273_06603
|
|
lib/matplotlib/axes/_base.py/_AxesBase/_process_unit_info
class _AxesBase: def _process_unit_info(self, datasets=None, kwargs=None, *, convert=True):
"""
Set axis units based on *datasets* and *kwargs*, and optionally apply
unit conversions to *datasets*.
Parameters
----------
datasets : list
List of (axis_name, dataset) pairs (where the axis name is defined
as in `._axis_map`). Individual datasets can also be None
(which gets passed through).
kwargs : dict
Other parameters from which unit info (i.e., the *xunits*,
*yunits*, *zunits* (for 3D Axes), *runits* and *thetaunits* (for
polar) entries) is popped, if present. Note that this dict is
mutated in-place!
convert : bool, default: True
Whether to return the original datasets or the converted ones.
Returns
-------
list
Either the original datasets if *convert* is False, or the
converted ones if *convert* is True (the default).
"""
# The API makes datasets a list of pairs rather than an axis_name to
# dataset mapping because it is sometimes necessary to process multiple
# datasets for a single axis, and concatenating them may be tricky
# (e.g. if some are scalars, etc.).
datasets = datasets or []
kwargs = kwargs or {}
axis_map = self._axis_map
for axis_name, data in datasets:
try:
axis = axis_map[axis_name]
except KeyError:
raise ValueError(f"Invalid axis name: {axis_name!r}") from None
# Update from data if axis is already set but no unit is set yet.
if axis is not None and data is not None and not axis.have_units():
axis.update_units(data)
for axis_name, axis in axis_map.items():
# Return if no axis is set.
if axis is None:
continue
# Check for units in the kwargs, and if present update axis.
units = kwargs.pop(f"{axis_name}units", axis.units)
if self.name == "polar":
# Special case: polar supports "thetaunits"/"runits".
polar_units = {"x": "thetaunits", "y": "runits"}
units = kwargs.pop(polar_units[axis_name], units)
if units != axis.units and units is not None:
axis.set_units(units)
# If the units being set imply a different converter,
# we need to update again.
for dataset_axis_name, data in datasets:
if dataset_axis_name == axis_name and data is not None:
axis.update_units(data)
return [axis_map[axis_name].convert_units(data)
if convert and data is not None else data
for axis_name, data in datasets]
|
negative_train_query273_06604
|
|
lib/matplotlib/axes/_base.py/_AxesBase/in_axes
class _AxesBase: def in_axes(self, mouseevent):
"""
Return whether the given event (in display coords) is in the Axes.
"""
return self.patch.contains(mouseevent)[0]
|
negative_train_query273_06605
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_autoscale_on
class _AxesBase: def get_autoscale_on(self):
"""Return True if each axis is autoscaled, False otherwise."""
return all(axis._get_autoscale_on()
for axis in self._axis_map.values())
|
negative_train_query273_06606
|
|
lib/matplotlib/axes/_base.py/_AxesBase/set_autoscale_on
class _AxesBase: def set_autoscale_on(self, b):
"""
Set whether autoscaling is applied to each axis on the next draw or
call to `.Axes.autoscale_view`.
Parameters
----------
b : bool
"""
for axis in self._axis_map.values():
axis._set_autoscale_on(b)
|
negative_train_query273_06607
|
|
lib/matplotlib/axes/_base.py/_AxesBase/use_sticky_edges
class _AxesBase: def use_sticky_edges(self, b):
self._use_sticky_edges = bool(b)
|
negative_train_query273_06608
|
|
lib/matplotlib/axes/_base.py/_AxesBase/set_xmargin
class _AxesBase: def set_xmargin(self, m):
"""
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. If *m* is negative, this will clip
the data range instead of expanding it.
For example, if your data is in the range [0, 2], a margin of 0.1 will
result in a range [-0.2, 2.2]; a margin of -0.1 will result in a range
of [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._request_autoscale_view("x")
self.stale = True
|
negative_train_query273_06609
|
|
lib/matplotlib/axes/_base.py/_AxesBase/set_ymargin
class _AxesBase: def set_ymargin(self, m):
"""
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. If *m* is negative, this will clip
the data range instead of expanding it.
For example, if your data is in the range [0, 2], a margin of 0.1 will
result in a range [-0.2, 2.2]; a margin of -0.1 will result in a range
of [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._request_autoscale_view("y")
self.stale = True
|
negative_train_query273_06610
|
|
lib/matplotlib/axes/_base.py/_AxesBase/margins
class _AxesBase: def margins(self, *margins, x=None, y=None, tight=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
----------
*margins : 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 or None, default: True
The *tight* parameter is passed to `~.axes.Axes.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. Setting *tight* to *None* preserves
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 or 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:
_api.warn_external(f'ignoring tight={tight!r} in get mode')
return self._xmargin, self._ymargin
if tight is not None:
self._tight = tight
if x is not None:
self.set_xmargin(x)
if y is not None:
self.set_ymargin(y)
|
negative_train_query273_06611
|
|
lib/matplotlib/axes/_base.py/_AxesBase/set_rasterization_zorder
class _AxesBase: def set_rasterization_zorder(self, z):
"""
Set the zorder threshold for rasterization for vector graphics output.
All artists with a zorder below the given value will be rasterized if
they support rasterization.
This setting is ignored for pixel-based output.
See also :doc:`/gallery/misc/rasterization_demo`.
Parameters
----------
z : float or None
The zorder below which artists are rasterized.
If ``None`` rasterization based on zorder is deactivated.
"""
self._rasterization_zorder = z
self.stale = True
|
negative_train_query273_06612
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_rasterization_zorder
class _AxesBase: def get_rasterization_zorder(self):
"""Return the zorder value below which artists will be rasterized."""
return self._rasterization_zorder
|
negative_train_query273_06613
|
|
lib/matplotlib/axes/_base.py/_AxesBase/autoscale
class _AxesBase: def autoscale(self, enable=True, axis='both', tight=None):
"""
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, default: True
True turns autoscaling on, False turns it off.
None leaves the autoscaling state unchanged.
axis : {'both', 'x', 'y'}, default: 'both'
The axis on which to operate. (For 3D Axes, *axis* can also be set
to 'z', and 'both' refers to all three axes.)
tight : bool or None, default: None
If True, first set the margins to zero. Then, this argument is
forwarded to `~.axes.Axes.autoscale_view` (regardless of
its value); see the description of its behavior there.
"""
if enable is None:
scalex = True
scaley = True
else:
if axis in ['x', 'both']:
self.set_autoscalex_on(bool(enable))
scalex = self.get_autoscalex_on()
else:
scalex = False
if axis in ['y', 'both']:
self.set_autoscaley_on(bool(enable))
scaley = self.get_autoscaley_on()
else:
scaley = False
if tight and scalex:
self._xmargin = 0
if tight and scaley:
self._ymargin = 0
if scalex:
self._request_autoscale_view("x", tight=tight)
if scaley:
self._request_autoscale_view("y", tight=tight)
|
negative_train_query273_06614
|
|
lib/matplotlib/axes/_base.py/_AxesBase/autoscale_view
class _AxesBase: def autoscale_view(self, tight=None, scalex=True, scaley=True):
"""
Autoscale the view limits using the data limits.
Parameters
----------
tight : bool or None
If *True*, only expand the axis limits using the margins. Note
that unlike for `autoscale`, ``tight=True`` does *not* set the
margins to zero.
If *False* and :rc:`axes.autolimit_mode` is 'round_numbers', then
after expansion by the margins, further expand the axis limits
using the axis major locator.
If None (the default), reuse the value set in the previous call to
`autoscale_view` (the initial value is False, but the default style
sets :rc:`axes.autolimit_mode` to 'data', in which case this
behaves like True).
scalex : bool, default: True
Whether to autoscale the x-axis.
scaley : bool, default: True
Whether to autoscale the y-axis.
Notes
-----
The autoscaling preserves any preexisting axis direction reversal.
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.
If the views of the Axes are fixed, e.g. via `set_xlim`, they will
not be changed by autoscale_view().
See :meth:`matplotlib.axes.Axes.autoscale` for an alternative.
"""
if tight is not None:
self._tight = bool(tight)
x_stickies = y_stickies = np.array([])
if self.use_sticky_edges:
if self._xmargin and scalex and self.get_autoscalex_on():
x_stickies = np.sort(np.concatenate([
artist.sticky_edges.x
for ax in self._shared_axes["x"].get_siblings(self)
for artist in ax.get_children()]))
if self._ymargin and scaley and self.get_autoscaley_on():
y_stickies = np.sort(np.concatenate([
artist.sticky_edges.y
for ax in self._shared_axes["y"].get_siblings(self)
for artist in ax.get_children()]))
if self.get_xscale() == 'log':
x_stickies = x_stickies[x_stickies > 0]
if self.get_yscale() == 'log':
y_stickies = y_stickies[y_stickies > 0]
def handle_single_axis(
scale, shared_axes, name, axis, margin, stickies, set_bound):
if not (scale and axis._get_autoscale_on()):
return # nothing to do...
shared = shared_axes.get_siblings(self)
# Base autoscaling on finite data limits when there is at least one
# finite data limit among all the shared_axes and intervals.
values = [val for ax in shared
for val in getattr(ax.dataLim, f"interval{name}")
if np.isfinite(val)]
if values:
x0, x1 = (min(values), max(values))
elif getattr(self._viewLim, f"mutated{name}")():
# No data, but explicit viewLims already set:
# in mutatedx or mutatedy.
return
else:
x0, x1 = (-np.inf, np.inf)
# If x0 and x1 are nonfinite, get default limits from the locator.
locator = axis.get_major_locator()
x0, x1 = locator.nonsingular(x0, x1)
# Find the minimum minpos for use in the margin calculation.
minimum_minpos = min(
getattr(ax.dataLim, f"minpos{name}") for ax in shared)
# Prevent margin addition from crossing a sticky value. A small
# tolerance must be added due to floating point issues with
# streamplot; it is defined relative to x0, x1, x1-x0 but has
# no absolute term (e.g. "+1e-8") to avoid issues when working with
# datasets where all values are tiny (less than 1e-8).
tol = 1e-5 * max(abs(x0), abs(x1), abs(x1 - x0))
# Index of largest element < x0 + tol, if any.
i0 = stickies.searchsorted(x0 + tol) - 1
x0bound = stickies[i0] if i0 != -1 else None
# Index of smallest element > x1 - tol, if any.
i1 = stickies.searchsorted(x1 - tol)
x1bound = stickies[i1] if i1 != len(stickies) else None
# Add the margin in figure space and then transform back, to handle
# non-linear scales.
transform = axis.get_transform()
inverse_trans = transform.inverted()
x0, x1 = axis._scale.limit_range_for_scale(x0, x1, minimum_minpos)
x0t, x1t = transform.transform([x0, x1])
delta = (x1t - x0t) * margin
if not np.isfinite(delta):
delta = 0 # If a bound isn't finite, set margin to zero.
x0, x1 = inverse_trans.transform([x0t - delta, x1t + delta])
# Apply sticky bounds.
if x0bound is not None:
x0 = max(x0, x0bound)
if x1bound is not None:
x1 = min(x1, x1bound)
if not self._tight:
x0, x1 = locator.view_limits(x0, x1)
set_bound(x0, x1)
# End of definition of internal function 'handle_single_axis'.
handle_single_axis(
scalex, self._shared_axes["x"], 'x', self.xaxis, self._xmargin,
x_stickies, self.set_xbound)
handle_single_axis(
scaley, self._shared_axes["y"], 'y', self.yaxis, self._ymargin,
y_stickies, self.set_ybound)
|
negative_train_query273_06615
|
|
lib/matplotlib/axes/_base.py/_AxesBase/_update_title_position
class _AxesBase: def _update_title_position(self, renderer):
"""
Update the title position based on the bounding box enclosing
all the ticklabels and x-axis spine and xlabel...
"""
if self._autotitlepos is not None and not self._autotitlepos:
_log.debug('title position was updated manually, not adjusting')
return
titles = (self.title, self._left_title, self._right_title)
# Need to check all our twins too, and all the children as well.
axs = self._twinned_axes.get_siblings(self) + self.child_axes
for ax in self.child_axes: # Child positions must be updated first.
locator = ax.get_axes_locator()
ax.apply_aspect(locator(self, renderer) if locator else None)
for title in titles:
x, _ = title.get_position()
# need to start again in case of window resizing
title.set_position((x, 1.0))
top = -np.inf
for ax in axs:
bb = None
if (ax.xaxis.get_ticks_position() in ['top', 'unknown']
or ax.xaxis.get_label_position() == 'top'):
bb = ax.xaxis.get_tightbbox(renderer)
if bb is None:
if 'outline' in ax.spines:
# Special case for colorbars:
bb = ax.spines['outline'].get_window_extent()
else:
bb = ax.get_window_extent(renderer)
top = max(top, bb.ymax)
if title.get_text():
ax.yaxis.get_tightbbox(renderer) # update offsetText
if ax.yaxis.offsetText.get_text():
bb = ax.yaxis.offsetText.get_tightbbox(renderer)
if bb.intersection(title.get_tightbbox(renderer), bb):
top = bb.ymax
if top < 0:
# the top of Axes is not even on the figure, so don't try and
# automatically place it.
_log.debug('top of Axes not in the figure, so title not moved')
return
if title.get_window_extent(renderer).ymin < top:
_, y = self.transAxes.inverted().transform((0, top))
title.set_position((x, y))
# empirically, this doesn't always get the min to top,
# so we need to adjust again.
if title.get_window_extent(renderer).ymin < top:
_, y = self.transAxes.inverted().transform(
(0., 2 * top - title.get_window_extent(renderer).ymin))
title.set_position((x, y))
ymax = max(title.get_position()[1] for title in titles)
for title in titles:
# now line up all the titles at the highest baseline.
x, _ = title.get_position()
title.set_position((x, ymax))
|
negative_train_query273_06616
|
|
lib/matplotlib/axes/_base.py/_AxesBase/draw
class _AxesBase: def draw(self, renderer):
# docstring inherited
if renderer is None:
raise RuntimeError('No renderer defined')
if not self.get_visible():
return
self._unstale_viewLim()
renderer.open_group('axes', gid=self.get_gid())
# prevent triggering call backs during the draw process
self._stale = True
# loop over self and child Axes...
locator = self.get_axes_locator()
self.apply_aspect(locator(self, renderer) if locator else None)
artists = self.get_children()
artists.remove(self.patch)
# 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.
if not (self.axison and self._frameon):
for spine in self.spines.values():
artists.remove(spine)
self._update_title_position(renderer)
if not self.axison:
for _axis in self._axis_map.values():
artists.remove(_axis)
if not self.figure.canvas.is_saving():
artists = [
a for a in artists
if not a.get_animated() or isinstance(a, mimage.AxesImage)]
artists = sorted(artists, key=attrgetter('zorder'))
# rasterize artists with negative zorder
# if the minimum zorder is negative, start rasterization
rasterization_zorder = self._rasterization_zorder
if (rasterization_zorder is not None and
artists and artists[0].zorder < rasterization_zorder):
split_index = np.searchsorted(
[art.zorder for art in artists],
rasterization_zorder, side='right'
)
artists_rasterized = artists[:split_index]
artists = artists[split_index:]
else:
artists_rasterized = []
if self.axison and self._frameon:
if artists_rasterized:
artists_rasterized = [self.patch] + artists_rasterized
else:
artists = [self.patch] + artists
if artists_rasterized:
_draw_rasterized(self.figure, artists_rasterized, renderer)
mimage._draw_list_compositing_images(
renderer, self, artists, self.figure.suppressComposite)
renderer.close_group('axes')
self.stale = False
|
negative_train_query273_06617
|
|
lib/matplotlib/axes/_base.py/_AxesBase/draw_artist
class _AxesBase: def draw_artist(self, a):
"""
Efficiently redraw a single artist.
"""
a.draw(self.figure.canvas.get_renderer())
|
negative_train_query273_06618
|
|
lib/matplotlib/axes/_base.py/_AxesBase/redraw_in_frame
class _AxesBase: def redraw_in_frame(self):
"""
Efficiently redraw Axes data, but not axis ticks, labels, etc.
"""
with ExitStack() as stack:
for artist in [*self._axis_map.values(),
self.title, self._left_title, self._right_title]:
stack.enter_context(artist._cm_set(visible=False))
self.draw(self.figure.canvas.get_renderer())
|
negative_train_query273_06619
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_renderer_cache
class _AxesBase: def get_renderer_cache(self):
return self.figure.canvas.get_renderer()
|
negative_train_query273_06620
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_frame_on
class _AxesBase: def get_frame_on(self):
"""Get whether the Axes rectangle patch is drawn."""
return self._frameon
|
negative_train_query273_06621
|
|
lib/matplotlib/axes/_base.py/_AxesBase/set_frame_on
class _AxesBase: def set_frame_on(self, b):
"""
Set whether the Axes rectangle patch is drawn.
Parameters
----------
b : bool
"""
self._frameon = b
self.stale = True
|
negative_train_query273_06622
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_axisbelow
class _AxesBase: def get_axisbelow(self):
"""
Get whether axis ticks and gridlines are above or below most artists.
Returns
-------
bool or 'line'
See Also
--------
set_axisbelow
"""
return self._axisbelow
|
negative_train_query273_06623
|
|
lib/matplotlib/axes/_base.py/_AxesBase/set_axisbelow
class _AxesBase: def set_axisbelow(self, b):
"""
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, with default zorder = 1) but still below lines
and markers (with their default zorder = 2).
- *False* (zorder = 2.5): Ticks and gridlines are above patches
and lines / markers.
See Also
--------
get_axisbelow
"""
# Check that b is True, False or 'line'
self._axisbelow = axisbelow = validate_axisbelow(b)
zorder = {
True: 0.5,
'line': 1.5,
False: 2.5,
}[axisbelow]
for axis in self._axis_map.values():
axis.set_zorder(zorder)
self.stale = True
|
negative_train_query273_06624
|
|
lib/matplotlib/axes/_base.py/_AxesBase/grid
class _AxesBase: def grid(self, visible=None, which='major', axis='both', **kwargs):
"""
Configure the grid lines.
Parameters
----------
visible : bool or None, optional
Whether to show the grid lines. If any *kwargs* are supplied, it
is assumed you want the grid on and *visible* will be set to True.
If *visible* is *None* and there are no *kwargs*, this toggles the
visibility of the lines.
which : {'major', 'minor', 'both'}, optional
The grid lines to apply the changes on.
axis : {'both', 'x', 'y'}, optional
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 keyword arguments are:
%(Line2D:kwdoc)s
Notes
-----
The axis is drawn as a unit, so the effective zorder for drawing the
grid is determined by the zorder of each axis, not by the zorder of the
`.Line2D` objects comprising the grid. Therefore, to set grid zorder,
use `.set_axisbelow` or, for more control, call the
`~.Artist.set_zorder` method of each axis.
"""
_api.check_in_list(['x', 'y', 'both'], axis=axis)
if axis in ['x', 'both']:
self.xaxis.grid(visible, which=which, **kwargs)
if axis in ['y', 'both']:
self.yaxis.grid(visible, which=which, **kwargs)
|
negative_train_query273_06625
|
|
lib/matplotlib/axes/_base.py/_AxesBase/ticklabel_format
class _AxesBase: def ticklabel_format(self, *, axis='both', style='', scilimits=None,
useOffset=None, useLocale=None, useMathText=None):
r"""
Configure the `.ScalarFormatter` used by default for linear Axes.
If a parameter is not set, the corresponding property of the formatter
is left unchanged.
Parameters
----------
axis : {'x', 'y', 'both'}, default: 'both'
The axis to configure. Only major ticks are affected.
style : {'sci', 'scientific', 'plain'}
Whether to use scientific notation.
The formatter default is to use scientific notation.
scilimits : pair of ints (m, n)
Scientific notation is used only for numbers outside the range
10\ :sup:`m` to 10\ :sup:`n` (and only if the formatter is
configured to use scientific notation at all). Use (0, 0) to
include all numbers. Use (m, m) where m != 0 to fix the order of
magnitude to 10\ :sup:`m`.
The formatter default is :rc:`axes.formatter.limits`.
useOffset : bool or float
If True, the offset is calculated as needed.
If False, no offset is used.
If a numeric value, it sets the offset.
The formatter default is :rc:`axes.formatter.useoffset`.
useLocale : bool
Whether to format the number using the current locale or using the
C (English) locale. This affects e.g. the decimal separator. The
formatter default is :rc:`axes.formatter.use_locale`.
useMathText : bool
Render the offset and scientific notation in mathtext.
The formatter default is :rc:`axes.formatter.use_mathtext`.
Raises
------
AttributeError
If the current formatter is not a `.ScalarFormatter`.
"""
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) as err:
raise ValueError("scilimits must be a sequence of 2 integers"
) from err
STYLES = {'sci': True, 'scientific': True, 'plain': False, '': None}
is_sci_style = _api.check_getitem(STYLES, style=style)
axis_map = {**{k: [v] for k, v in self._axis_map.items()},
'both': list(self._axis_map.values())}
axises = _api.check_getitem(axis_map, axis=axis)
try:
for axis in axises:
if is_sci_style is not None:
axis.major.formatter.set_scientific(is_sci_style)
if scilimits is not None:
axis.major.formatter.set_powerlimits(scilimits)
if useOffset is not None:
axis.major.formatter.set_useOffset(useOffset)
if useLocale is not None:
axis.major.formatter.set_useLocale(useLocale)
if useMathText is not None:
axis.major.formatter.set_useMathText(useMathText)
except AttributeError as err:
raise AttributeError(
"This method only works with the ScalarFormatter") from err
|
negative_train_query273_06626
|
|
lib/matplotlib/axes/_base.py/_AxesBase/locator_params
class _AxesBase: def locator_params(self, axis='both', tight=None, **kwargs):
"""
Control behavior of major tick locators.
Because the locator is involved in autoscaling, `~.Axes.autoscale_view`
is called automatically after the parameters are changed.
Parameters
----------
axis : {'both', 'x', 'y'}, default: 'both'
The axis on which to operate. (For 3D Axes, *axis* can also be
set to 'z', and 'both' refers to all three axes.)
tight : bool or None, optional
Parameter passed to `~.Axes.autoscale_view`.
Default is None, for no change.
Other Parameters
----------------
**kwargs
Remaining keyword arguments are passed to directly to the
``set_params()`` method of the locator. Supported keywords depend
on the type of the locator. See for example
`~.ticker.MaxNLocator.set_params` for the `.ticker.MaxNLocator`
used by default for linear.
Examples
--------
When plotting small subplots, one might want to reduce the maximum
number of ticks and use tight bounds, for example::
ax.locator_params(tight=True, nbins=4)
"""
_api.check_in_list([*self._axis_names, "both"], axis=axis)
for name in self._axis_names:
if axis in [name, "both"]:
loc = self._axis_map[name].get_major_locator()
loc.set_params(**kwargs)
self._request_autoscale_view(name, tight=tight)
self.stale = True
|
negative_train_query273_06627
|
|
lib/matplotlib/axes/_base.py/_AxesBase/tick_params
class _AxesBase: def tick_params(self, axis='both', **kwargs):
"""
Change the appearance of ticks, tick labels, and gridlines.
Tick properties that are not explicitly set using the keyword
arguments remain unchanged unless *reset* is True. For the current
style settings, see `.Axis.get_tick_params`.
Parameters
----------
axis : {'x', 'y', 'both'}, default: 'both'
The axis to which the parameters are applied.
which : {'major', 'minor', 'both'}, default: 'major'
The group of ticks to which the parameters are applied.
reset : bool, default: False
Whether to reset the ticks to defaults before updating them.
Other Parameters
----------------
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.
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.
colors : color
Tick color and label color.
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
Gridline color.
grid_alpha : float
Transparency of gridlines: 0 (transparent) to 1 (opaque).
grid_linewidth : float
Width of gridlines in points.
grid_linestyle : str
Any valid `.Line2D` line style spec.
Examples
--------
::
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.
"""
_api.check_in_list(['x', 'y', 'both'], axis=axis)
if axis in ['x', 'both']:
xkw = dict(kwargs)
xkw.pop('left', None)
xkw.pop('right', None)
xkw.pop('labelleft', None)
xkw.pop('labelright', None)
self.xaxis.set_tick_params(**xkw)
if axis in ['y', 'both']:
ykw = dict(kwargs)
ykw.pop('top', None)
ykw.pop('bottom', None)
ykw.pop('labeltop', None)
ykw.pop('labelbottom', None)
self.yaxis.set_tick_params(**ykw)
|
negative_train_query273_06628
|
|
lib/matplotlib/axes/_base.py/_AxesBase/set_axis_off
class _AxesBase: def set_axis_off(self):
"""
Turn the x- and y-axis off.
This affects the axis lines, ticks, ticklabels, grid and axis labels.
"""
self.axison = False
self.stale = True
|
negative_train_query273_06629
|
|
lib/matplotlib/axes/_base.py/_AxesBase/set_axis_on
class _AxesBase: def set_axis_on(self):
"""
Turn the x- and y-axis on.
This affects the axis lines, ticks, ticklabels, grid and axis labels.
"""
self.axison = True
self.stale = True
|
negative_train_query273_06630
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_xlabel
class _AxesBase: def get_xlabel(self):
"""
Get the xlabel text string.
"""
label = self.xaxis.get_label()
return label.get_text()
|
negative_train_query273_06631
|
|
lib/matplotlib/axes/_base.py/_AxesBase/set_xlabel
class _AxesBase: def set_xlabel(self, xlabel, fontdict=None, labelpad=None, *,
loc=None, **kwargs):
"""
Set the label for the x-axis.
Parameters
----------
xlabel : str
The label text.
labelpad : float, default: :rc:`axes.labelpad`
Spacing in points from the Axes bounding box including ticks
and tick labels. If None, the previous value is left as is.
loc : {'left', 'center', 'right'}, default: :rc:`xaxis.labellocation`
The label position. This is a high-level alternative for passing
parameters *x* and *horizontalalignment*.
Other Parameters
----------------
**kwargs : `.Text` properties
`.Text` properties control the appearance of the label.
See Also
--------
text : Documents the properties supported by `.Text`.
"""
if labelpad is not None:
self.xaxis.labelpad = labelpad
protected_kw = ['x', 'horizontalalignment', 'ha']
if {*kwargs} & {*protected_kw}:
if loc is not None:
raise TypeError(f"Specifying 'loc' is disallowed when any of "
f"its corresponding low level keyword "
f"arguments ({protected_kw}) are also "
f"supplied")
else:
loc = (loc if loc is not None
else mpl.rcParams['xaxis.labellocation'])
_api.check_in_list(('left', 'center', 'right'), loc=loc)
x = {
'left': 0,
'center': 0.5,
'right': 1,
}[loc]
kwargs.update(x=x, horizontalalignment=loc)
return self.xaxis.set_label_text(xlabel, fontdict, **kwargs)
|
negative_train_query273_06632
|
|
lib/matplotlib/axes/_base.py/_AxesBase/invert_xaxis
class _AxesBase: def invert_xaxis(self):
"""
Invert the x-axis.
See Also
--------
xaxis_inverted
get_xlim, set_xlim
get_xbound, set_xbound
"""
self.xaxis.set_inverted(not self.xaxis.get_inverted())
|
negative_train_query273_06633
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_xbound
class _AxesBase: def get_xbound(self):
"""
Return the lower and upper x-axis bounds, in increasing order.
See Also
--------
set_xbound
get_xlim, set_xlim
invert_xaxis, xaxis_inverted
"""
left, right = self.get_xlim()
if left < right:
return left, right
else:
return right, left
|
negative_train_query273_06634
|
|
lib/matplotlib/axes/_base.py/_AxesBase/set_xbound
class _AxesBase: def set_xbound(self, lower=None, upper=None):
"""
Set the lower and upper numerical bounds of the x-axis.
This method will honor axis inversion regardless of parameter order.
It will not change the autoscaling setting (`.get_autoscalex_on()`).
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
"""
if upper is None and np.iterable(lower):
lower, upper = lower
old_lower, old_upper = self.get_xbound()
if lower is None:
lower = old_lower
if upper is None:
upper = old_upper
self.set_xlim(sorted((lower, upper),
reverse=bool(self.xaxis_inverted())),
auto=None)
|
negative_train_query273_06635
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_xlim
class _AxesBase: def get_xlim(self):
"""
Return the x-axis view limits.
Returns
-------
left, right : (float, float)
The current x-axis limits in data coordinates.
See Also
--------
.Axes.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.
"""
return tuple(self.viewLim.intervalx)
|
negative_train_query273_06636
|
|
lib/matplotlib/axes/_base.py/_AxesBase/_validate_converted_limits
class _AxesBase: def _validate_converted_limits(self, limit, convert):
"""
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.
"""
if limit is not None:
converted_limit = convert(limit)
if (isinstance(converted_limit, Real)
and not np.isfinite(converted_limit)):
raise ValueError("Axis limits cannot be NaN or Inf")
return converted_limit
|
negative_train_query273_06637
|
|
lib/matplotlib/axes/_base.py/_AxesBase/set_xlim
class _AxesBase: def set_xlim(self, left=None, right=None, emit=True, auto=False,
*, xmin=None, xmax=None):
"""
Set the x-axis view limits.
Parameters
----------
left : float, optional
The left xlim in data coordinates. Passing *None* leaves the
limit unchanged.
The left and right xlims may also be passed as the tuple
(*left*, *right*) as the first positional argument (or as
the *left* keyword argument).
.. ACCEPTS: (bottom: float, top: float)
right : float, optional
The right xlim in data coordinates. Passing *None* leaves the
limit unchanged.
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.
xmin, xmax : float, optional
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)
"""
if right is None and np.iterable(left):
left, right = left
if xmin is not None:
if left is not None:
raise TypeError("Cannot pass both 'left' and 'xmin'")
left = xmin
if xmax is not None:
if right is not None:
raise TypeError("Cannot pass both 'right' and 'xmax'")
right = xmax
return self.xaxis._set_lim(left, right, emit=emit, auto=auto)
|
negative_train_query273_06638
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_ylabel
class _AxesBase: def get_ylabel(self):
"""
Get the ylabel text string.
"""
label = self.yaxis.get_label()
return label.get_text()
|
negative_train_query273_06639
|
|
lib/matplotlib/axes/_base.py/_AxesBase/set_ylabel
class _AxesBase: def set_ylabel(self, ylabel, fontdict=None, labelpad=None, *,
loc=None, **kwargs):
"""
Set the label for the y-axis.
Parameters
----------
ylabel : str
The label text.
labelpad : float, default: :rc:`axes.labelpad`
Spacing in points from the Axes bounding box including ticks
and tick labels. If None, the previous value is left as is.
loc : {'bottom', 'center', 'top'}, default: :rc:`yaxis.labellocation`
The label position. This is a high-level alternative for passing
parameters *y* and *horizontalalignment*.
Other Parameters
----------------
**kwargs : `.Text` properties
`.Text` properties control the appearance of the label.
See Also
--------
text : Documents the properties supported by `.Text`.
"""
if labelpad is not None:
self.yaxis.labelpad = labelpad
protected_kw = ['y', 'horizontalalignment', 'ha']
if {*kwargs} & {*protected_kw}:
if loc is not None:
raise TypeError(f"Specifying 'loc' is disallowed when any of "
f"its corresponding low level keyword "
f"arguments ({protected_kw}) are also "
f"supplied")
else:
loc = (loc if loc is not None
else mpl.rcParams['yaxis.labellocation'])
_api.check_in_list(('bottom', 'center', 'top'), loc=loc)
y, ha = {
'bottom': (0, 'left'),
'center': (0.5, 'center'),
'top': (1, 'right')
}[loc]
kwargs.update(y=y, horizontalalignment=ha)
return self.yaxis.set_label_text(ylabel, fontdict, **kwargs)
|
negative_train_query273_06640
|
|
lib/matplotlib/axes/_base.py/_AxesBase/invert_yaxis
class _AxesBase: def invert_yaxis(self):
"""
Invert the y-axis.
See Also
--------
yaxis_inverted
get_ylim, set_ylim
get_ybound, set_ybound
"""
self.yaxis.set_inverted(not self.yaxis.get_inverted())
|
negative_train_query273_06641
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_ybound
class _AxesBase: def get_ybound(self):
"""
Return the lower and upper y-axis bounds, in increasing order.
See Also
--------
set_ybound
get_ylim, set_ylim
invert_yaxis, yaxis_inverted
"""
bottom, top = self.get_ylim()
if bottom < top:
return bottom, top
else:
return top, bottom
|
negative_train_query273_06642
|
|
lib/matplotlib/axes/_base.py/_AxesBase/set_ybound
class _AxesBase: def set_ybound(self, lower=None, upper=None):
"""
Set the lower and upper numerical bounds of the y-axis.
This method will honor axis inversion regardless of parameter order.
It will not change the autoscaling setting (`.get_autoscaley_on()`).
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
"""
if upper is None and np.iterable(lower):
lower, upper = lower
old_lower, old_upper = self.get_ybound()
if lower is None:
lower = old_lower
if upper is None:
upper = old_upper
self.set_ylim(sorted((lower, upper),
reverse=bool(self.yaxis_inverted())),
auto=None)
|
negative_train_query273_06643
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_ylim
class _AxesBase: def get_ylim(self):
"""
Return the y-axis view limits.
Returns
-------
bottom, top : (float, float)
The current y-axis limits in data coordinates.
See Also
--------
.Axes.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.
"""
return tuple(self.viewLim.intervaly)
|
negative_train_query273_06644
|
|
lib/matplotlib/axes/_base.py/_AxesBase/set_ylim
class _AxesBase: def set_ylim(self, bottom=None, top=None, emit=True, auto=False,
*, ymin=None, ymax=None):
"""
Set the y-axis view limits.
Parameters
----------
bottom : float, optional
The bottom ylim in data coordinates. Passing *None* leaves the
limit unchanged.
The bottom and top ylims may also be passed as the tuple
(*bottom*, *top*) as the first positional argument (or as
the *bottom* keyword argument).
.. ACCEPTS: (bottom: float, top: float)
top : float, optional
The top ylim in data coordinates. Passing *None* leaves the
limit unchanged.
emit : bool, default: True
Whether to notify observers of limit change.
auto : bool or None, default: False
Whether to turn on autoscaling of the y-axis. *True* turns on,
*False* turns off, *None* leaves unchanged.
ymin, ymax : float, optional
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)
"""
if top is None and np.iterable(bottom):
bottom, top = bottom
if ymin is not None:
if bottom is not None:
raise TypeError("Cannot pass both 'bottom' and 'ymin'")
bottom = ymin
if ymax is not None:
if top is not None:
raise TypeError("Cannot pass both 'top' and 'ymax'")
top = ymax
return self.yaxis._set_lim(bottom, top, emit=emit, auto=auto)
|
negative_train_query273_06645
|
|
lib/matplotlib/axes/_base.py/_AxesBase/format_xdata
class _AxesBase: def format_xdata(self, x):
"""
Return *x* formatted as an x-value.
This function will use the `.fmt_xdata` attribute if it is not None,
else will fall back on the xaxis major formatter.
"""
return (self.fmt_xdata if self.fmt_xdata is not None
else self.xaxis.get_major_formatter().format_data_short)(x)
|
negative_train_query273_06646
|
|
lib/matplotlib/axes/_base.py/_AxesBase/format_ydata
class _AxesBase: def format_ydata(self, y):
"""
Return *y* formatted as a y-value.
This function will use the `.fmt_ydata` attribute if it is not None,
else will fall back on the yaxis major formatter.
"""
return (self.fmt_ydata if self.fmt_ydata is not None
else self.yaxis.get_major_formatter().format_data_short)(y)
|
negative_train_query273_06647
|
|
lib/matplotlib/axes/_base.py/_AxesBase/format_coord
class _AxesBase: def format_coord(self, x, y):
"""Return a format string formatting the *x*, *y* coordinates."""
return "x={} y={}".format(
"???" if x is None else self.format_xdata(x),
"???" if y is None else self.format_ydata(y),
)
|
negative_train_query273_06648
|
|
lib/matplotlib/axes/_base.py/_AxesBase/minorticks_on
class _AxesBase: def minorticks_on(self):
"""
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())
|
negative_train_query273_06649
|
|
lib/matplotlib/axes/_base.py/_AxesBase/minorticks_off
class _AxesBase: def minorticks_off(self):
"""Remove minor ticks from the Axes."""
self.xaxis.set_minor_locator(mticker.NullLocator())
self.yaxis.set_minor_locator(mticker.NullLocator())
|
negative_train_query273_06650
|
|
lib/matplotlib/axes/_base.py/_AxesBase/can_zoom
class _AxesBase: def can_zoom(self):
"""
Return whether this Axes supports the zoom box button functionality.
"""
return True
|
negative_train_query273_06651
|
|
lib/matplotlib/axes/_base.py/_AxesBase/can_pan
class _AxesBase: def can_pan(self):
"""
Return whether this Axes supports any pan/zoom button functionality.
"""
return True
|
negative_train_query273_06652
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_navigate
class _AxesBase: def get_navigate(self):
"""
Get whether the Axes responds to navigation commands.
"""
return self._navigate
|
negative_train_query273_06653
|
|
lib/matplotlib/axes/_base.py/_AxesBase/set_navigate
class _AxesBase: def set_navigate(self, b):
"""
Set whether the Axes responds to navigation toolbar commands.
Parameters
----------
b : bool
"""
self._navigate = b
|
negative_train_query273_06654
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_navigate_mode
class _AxesBase: def get_navigate_mode(self):
"""
Get the navigation toolbar button status: 'PAN', 'ZOOM', or None.
"""
return self._navigate_mode
|
negative_train_query273_06655
|
|
lib/matplotlib/axes/_base.py/_AxesBase/set_navigate_mode
class _AxesBase: def set_navigate_mode(self, b):
"""
Set the navigation toolbar button status.
.. warning::
This is not a user-API function.
"""
self._navigate_mode = b
|
negative_train_query273_06656
|
|
lib/matplotlib/axes/_base.py/_AxesBase/_get_view
class _AxesBase: def _get_view(self):
"""
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
|
negative_train_query273_06657
|
|
lib/matplotlib/axes/_base.py/_AxesBase/_set_view
class _AxesBase: def _set_view(self, view):
"""
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))
|
negative_train_query273_06658
|
|
lib/matplotlib/axes/_base.py/_AxesBase/_prepare_view_from_bbox
class _AxesBase: def _prepare_view_from_bbox(self, bbox, direction='in',
mode=None, twinx=False, twiny=False):
"""
Helper function to prepare the new bounds from a bbox.
This helper function returns the new x and y bounds from the zoom
bbox. This a convenience method to abstract the bbox logic
out of the base setter.
"""
if len(bbox) == 3:
xp, yp, scl = bbox # Zooming code
if scl == 0: # Should not happen
scl = 1.
if scl > 1:
direction = 'in'
else:
direction = 'out'
scl = 1/scl
# get the limits of the axes
(xmin, ymin), (xmax, ymax) = self.transData.transform(
np.transpose([self.get_xlim(), self.get_ylim()]))
# 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
_api.warn_external(
"Warning in _set_view_from_bbox: bounding box is not a tuple "
"of length 3 or 4. Ignoring the view change.")
return
# Original limits.
xmin0, xmax0 = self.get_xbound()
ymin0, ymax0 = self.get_ybound()
# The zoom box in screen coords.
startx, starty, stopx, stopy = bbox
# Convert to data coords.
(startx, starty), (stopx, stopy) = self.transData.inverted().transform(
[(startx, starty), (stopx, stopy)])
# Clip to axes limits.
xmin, xmax = np.clip(sorted([startx, stopx]), xmin0, xmax0)
ymin, ymax = np.clip(sorted([starty, stopy]), ymin0, ymax0)
# Don't double-zoom twinned axes or if zooming only the other axis.
if twinx or mode == "y":
xmin, xmax = xmin0, xmax0
if twiny or mode == "x":
ymin, ymax = ymin0, ymax0
if direction == "in":
new_xbound = xmin, xmax
new_ybound = ymin, ymax
elif direction == "out":
x_trf = self.xaxis.get_transform()
sxmin0, sxmax0, sxmin, sxmax = x_trf.transform(
[xmin0, xmax0, xmin, xmax]) # To screen space.
factor = (sxmax0 - sxmin0) / (sxmax - sxmin) # Unzoom factor.
# Move original bounds away by
# (factor) x (distance between unzoom box and Axes bbox).
sxmin1 = sxmin0 - factor * (sxmin - sxmin0)
sxmax1 = sxmax0 + factor * (sxmax0 - sxmax)
# And back to data space.
new_xbound = x_trf.inverted().transform([sxmin1, sxmax1])
y_trf = self.yaxis.get_transform()
symin0, symax0, symin, symax = y_trf.transform(
[ymin0, ymax0, ymin, ymax])
factor = (symax0 - symin0) / (symax - symin)
symin1 = symin0 - factor * (symin - symin0)
symax1 = symax0 + factor * (symax0 - symax)
new_ybound = y_trf.inverted().transform([symin1, symax1])
return new_xbound, new_ybound
|
negative_train_query273_06659
|
|
lib/matplotlib/axes/_base.py/_AxesBase/_set_view_from_bbox
class _AxesBase: def _set_view_from_bbox(self, bbox, direction='in',
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.
"""
new_xbound, new_ybound = self._prepare_view_from_bbox(
bbox, direction=direction, mode=mode, twinx=twinx, twiny=twiny)
if not twinx and mode != "y":
self.set_xbound(new_xbound)
self.set_autoscalex_on(False)
if not twiny and mode != "x":
self.set_ybound(new_ybound)
self.set_autoscaley_on(False)
|
negative_train_query273_06660
|
|
lib/matplotlib/axes/_base.py/_AxesBase/start_pan
class _AxesBase: def start_pan(self, x, y, button):
"""
Called when a pan operation has started.
Parameters
----------
x, y : float
The mouse coordinates in display coords.
button : `.MouseButton`
The pressed mouse button.
Notes
-----
This is 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)
|
negative_train_query273_06661
|
|
lib/matplotlib/axes/_base.py/_AxesBase/end_pan
class _AxesBase: def end_pan(self):
"""
Called when a pan operation completes (when the mouse button is up.)
Notes
-----
This is intended to be overridden by new projection types.
"""
del self._pan_start
|
negative_train_query273_06662
|
|
lib/matplotlib/axes/_base.py/_AxesBase/_get_pan_points
class _AxesBase: def _get_pan_points(self, button, key, x, y):
"""
Helper function to return the new points after a pan.
This helper function returns the points on the axis after a pan has
occurred. This is a convenience method to abstract the pan logic
out of the base setter.
"""
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:
_api.warn_external('Overflow while panning')
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
return points
|
negative_train_query273_06663
|
|
lib/matplotlib/axes/_base.py/_AxesBase/drag_pan
class _AxesBase: def drag_pan(self, button, key, x, y):
"""
Called when the mouse moves during a pan operation.
Parameters
----------
button : `.MouseButton`
The pressed mouse button.
key : str or None
The pressed key, if any.
x, y : float
The mouse coordinates in display coords.
Notes
-----
This is intended to be overridden by new projection types.
"""
points = self._get_pan_points(button, key, x, y)
if points is not None:
self.set_xlim(points[:, 0])
self.set_ylim(points[:, 1])
|
negative_train_query273_06664
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_children
class _AxesBase: def get_children(self):
# docstring inherited.
return [
*self._children,
*self.spines.values(),
*self._axis_map.values(),
self.title, self._left_title, self._right_title,
*self.child_axes,
*([self.legend_] if self.legend_ is not None else []),
self.patch,
]
|
negative_train_query273_06665
|
|
lib/matplotlib/axes/_base.py/_AxesBase/contains
class _AxesBase: def contains(self, mouseevent):
# docstring inherited.
inside, info = self._default_contains(mouseevent)
if inside is not None:
return inside, info
return self.patch.contains(mouseevent)
|
negative_train_query273_06666
|
|
lib/matplotlib/axes/_base.py/_AxesBase/contains_point
class _AxesBase: def contains_point(self, point):
"""
Return whether *point* (pair of pixel coordinates) is inside the Axes
patch.
"""
return self.patch.contains_point(point, radius=1.0)
|
negative_train_query273_06667
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_default_bbox_extra_artists
class _AxesBase: def get_default_bbox_extra_artists(self):
"""
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()
for axis in self._axis_map.values():
# axis tight bboxes are calculated separately inside
# Axes.get_tightbbox() using for_layout_only=True
artists.remove(axis)
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)
artists.remove(self.title)
artists.remove(self._left_title)
artists.remove(self._right_title)
# always include types that do not internally implement clipping
# to Axes. may have clip_on set to True and clip_box equivalent
# to ax.bbox but then ignore these properties during draws.
noclip = (_AxesBase, maxis.Axis,
offsetbox.AnnotationBbox, offsetbox.OffsetBox)
return [a for a in artists if a.get_visible() and a.get_in_layout()
and (isinstance(a, noclip) or not a._fully_clipped_to_axes())]
|
negative_train_query273_06668
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_tightbbox
class _AxesBase: def get_tightbbox(self, renderer=None, call_axes_locator=True,
bbox_extra_artists=None, *, for_layout_only=False):
"""
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` subclass
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 : bool, 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.
for_layout_only : default: False
The bounding box will *not* include the x-extent of the title and
the xlabel, or the y-extent of the ylabel.
Returns
-------
`.BboxBase`
Bounding box in figure pixel coordinates.
See Also
--------
matplotlib.axes.Axes.get_window_extent
matplotlib.axis.Axis.get_tightbbox
matplotlib.spines.Spine.get_window_extent
"""
bb = []
if renderer is None:
renderer = self.figure._get_renderer()
if not self.get_visible():
return None
locator = self.get_axes_locator()
self.apply_aspect(
locator(self, renderer) if locator and call_axes_locator else None)
for axis in self._axis_map.values():
if self.axison and axis.get_visible():
ba = martist._get_tightbbox_for_layout_only(axis, renderer)
if ba:
bb.append(ba)
self._update_title_position(renderer)
axbbox = self.get_window_extent(renderer)
bb.append(axbbox)
for title in [self.title, self._left_title, self._right_title]:
if title.get_visible():
bt = title.get_window_extent(renderer)
if for_layout_only and bt.width > 0:
# make the title bbox 1 pixel wide so its width
# is not accounted for in bbox calculations in
# tight/constrained_layout
bt.x0 = (bt.x0 + bt.x1) / 2 - 0.5
bt.x1 = bt.x0 + 1.0
bb.append(bt)
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 0 < bbox.width < np.inf
and 0 < bbox.height < np.inf):
bb.append(bbox)
return mtransforms.Bbox.union(
[b for b in bb if b.width != 0 or b.height != 0])
|
negative_train_query273_06669
|
|
lib/matplotlib/axes/_base.py/_AxesBase/_make_twin_axes
class _AxesBase: def _make_twin_axes(self, *args, **kwargs):
"""Make a twinx Axes of self. This is used for twinx and twiny."""
if 'sharex' in kwargs and 'sharey' in kwargs:
# The following line is added in v2.2 to avoid breaking Seaborn,
# which currently uses this internal API.
if kwargs["sharex"] is not self and kwargs["sharey"] is not self:
raise ValueError("Twinned Axes may share only one axis")
ss = self.get_subplotspec()
if ss:
twin = self.figure.add_subplot(ss, *args, **kwargs)
else:
twin = self.figure.add_axes(
self.get_position(True), *args, **kwargs,
axes_locator=_TransformedBoundsLocator(
[0, 0, 1, 1], self.transAxes))
self.set_adjustable('datalim')
twin.set_adjustable('datalim')
self._twinned_axes.join(self, twin)
return twin
|
negative_train_query273_06670
|
|
lib/matplotlib/axes/_base.py/_AxesBase/twinx
class _AxesBase: def twinx(self):
"""
Create a twin Axes sharing the xaxis.
Create a new Axes 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
-------
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.
"""
ax2 = self._make_twin_axes(sharex=self)
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position('right')
ax2.yaxis.set_offset_position('right')
ax2.set_autoscalex_on(self.get_autoscalex_on())
self.yaxis.tick_left()
ax2.xaxis.set_visible(False)
ax2.patch.set_visible(False)
return ax2
|
negative_train_query273_06671
|
|
lib/matplotlib/axes/_base.py/_AxesBase/twiny
class _AxesBase: def twiny(self):
"""
Create a twin Axes sharing the yaxis.
Create a new Axes 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
-------
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
|
negative_train_query273_06672
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_shared_x_axes
class _AxesBase: def get_shared_x_axes(self):
"""Return an immutable view on the shared x-axes Grouper."""
return cbook.GrouperView(self._shared_axes["x"])
|
negative_train_query273_06673
|
|
lib/matplotlib/axes/_base.py/_AxesBase/get_shared_y_axes
class _AxesBase: def get_shared_y_axes(self):
"""Return an immutable view on the shared y-axes Grouper."""
return cbook.GrouperView(self._shared_axes["y"])
|
negative_train_query273_06674
|
|
lib/matplotlib/axes/_base.py/_AxesBase/label_outer
class _AxesBase: def label_outer(self):
"""
Only show "outer" labels and tick labels.
x-labels are only kept for subplots on the last row (or first row, if
labels are on the top side); y-labels only for subplots on the first
column (or last column, if labels are on the right side).
"""
self._label_outer_xaxis(check_patch=False)
self._label_outer_yaxis(check_patch=False)
|
negative_train_query273_06675
|
|
lib/matplotlib/axes/_base.py/_AxesBase/_label_outer_xaxis
class _AxesBase: def _label_outer_xaxis(self, *, check_patch):
# see documentation in label_outer.
if check_patch and not isinstance(self.patch, mpl.patches.Rectangle):
return
ss = self.get_subplotspec()
if not ss:
return
label_position = self.xaxis.get_label_position()
if not ss.is_first_row(): # Remove top label/ticklabels/offsettext.
if label_position == "top":
self.set_xlabel("")
self.xaxis.set_tick_params(which="both", labeltop=False)
if self.xaxis.offsetText.get_position()[1] == 1:
self.xaxis.offsetText.set_visible(False)
if not ss.is_last_row(): # Remove bottom label/ticklabels/offsettext.
if label_position == "bottom":
self.set_xlabel("")
self.xaxis.set_tick_params(which="both", labelbottom=False)
if self.xaxis.offsetText.get_position()[1] == 0:
self.xaxis.offsetText.set_visible(False)
|
negative_train_query273_06676
|
|
lib/matplotlib/axes/_base.py/_AxesBase/_label_outer_yaxis
class _AxesBase: def _label_outer_yaxis(self, *, check_patch):
# see documentation in label_outer.
if check_patch and not isinstance(self.patch, mpl.patches.Rectangle):
return
ss = self.get_subplotspec()
if not ss:
return
label_position = self.yaxis.get_label_position()
if not ss.is_first_col(): # Remove left label/ticklabels/offsettext.
if label_position == "left":
self.set_ylabel("")
self.yaxis.set_tick_params(which="both", labelleft=False)
if self.yaxis.offsetText.get_position()[0] == 0:
self.yaxis.offsetText.set_visible(False)
if not ss.is_last_col(): # Remove right label/ticklabels/offsettext.
if label_position == "right":
self.set_ylabel("")
self.yaxis.set_tick_params(which="both", labelright=False)
if self.yaxis.offsetText.get_position()[0] == 1:
self.yaxis.offsetText.set_visible(False)
|
negative_train_query273_06677
|
|
lib/matplotlib/axes/_base.py/ArtistList/__init__
class ArtistList: def __init__(self, axes, prop_name,
valid_types=None, invalid_types=None):
"""
Parameters
----------
axes : `~matplotlib.axes.Axes`
The Axes from which this sublist will pull the children
Artists.
prop_name : str
The property name used to access this sublist from the Axes;
used to generate deprecation warnings.
valid_types : list of type, optional
A list of types that determine which children will be returned
by this sublist. If specified, then the Artists in the sublist
must be instances of any of these types. If unspecified, then
any type of Artist is valid (unless limited by
*invalid_types*.)
invalid_types : tuple, optional
A list of types that determine which children will *not* be
returned by this sublist. If specified, then Artists in the
sublist will never be an instance of these types. Otherwise, no
types will be excluded.
"""
self._axes = axes
self._prop_name = prop_name
self._type_check = lambda artist: (
(not valid_types or isinstance(artist, valid_types)) and
(not invalid_types or not isinstance(artist, invalid_types))
)
|
negative_train_query273_06678
|
|
lib/matplotlib/axes/_base.py/ArtistList/__repr__
class ArtistList: def __repr__(self):
return f'<Axes.ArtistList of {len(self)} {self._prop_name}>'
|
negative_train_query273_06679
|
|
lib/matplotlib/axes/_base.py/ArtistList/__len__
class ArtistList: def __len__(self):
return sum(self._type_check(artist)
for artist in self._axes._children)
|
negative_train_query273_06680
|
|
lib/matplotlib/axes/_base.py/ArtistList/__iter__
class ArtistList: def __iter__(self):
for artist in list(self._axes._children):
if self._type_check(artist):
yield artist
|
negative_train_query273_06681
|
|
lib/matplotlib/axes/_base.py/ArtistList/__getitem__
class ArtistList: def __getitem__(self, key):
return [artist
for artist in self._axes._children
if self._type_check(artist)][key]
|
negative_train_query273_06682
|
|
lib/matplotlib/axes/_base.py/ArtistList/__add__
class ArtistList: def __add__(self, other):
if isinstance(other, (list, _AxesBase.ArtistList)):
return [*self, *other]
if isinstance(other, (tuple, _AxesBase.ArtistList)):
return (*self, *other)
return NotImplemented
|
negative_train_query273_06683
|
|
lib/matplotlib/axes/_base.py/ArtistList/__radd__
class ArtistList: def __radd__(self, other):
if isinstance(other, list):
return other + list(self)
if isinstance(other, tuple):
return other + tuple(self)
return NotImplemented
|
negative_train_query273_06684
|
|
lib/matplotlib/axes/_base.py/_MinimalArtist/get_rasterized
class _MinimalArtist: def get_rasterized(self):
return True
|
negative_train_query273_06685
|
|
lib/matplotlib/axes/_base.py/_MinimalArtist/get_agg_filter
class _MinimalArtist: def get_agg_filter(self):
return None
|
negative_train_query273_06686
|
|
lib/matplotlib/axes/_base.py/_MinimalArtist/__init__
class _MinimalArtist: def __init__(self, figure, artists):
self.figure = figure
self.artists = artists
|
negative_train_query273_06687
|
|
lib/matplotlib/axes/_base.py/_MinimalArtist/draw
class _MinimalArtist: def draw(self, renderer):
for a in self.artists:
a.draw(renderer)
|
negative_train_query273_06688
|
|
matplotlib/setupext.py/_get_xdg_cache_dir
def _get_xdg_cache_dir():
"""
Return the `XDG cache directory`__.
__ https://specifications.freedesktop.org/basedir-spec/latest/
"""
cache_dir = os.environ.get('XDG_CACHE_HOME')
if not cache_dir:
cache_dir = os.path.expanduser('~/.cache')
if cache_dir.startswith('~/'): # Expansion failed.
return None
return Path(cache_dir, 'matplotlib')
|
negative_train_query273_06689
|
|
matplotlib/setupext.py/_get_hash
def _get_hash(data):
"""Compute the sha256 hash of *data*."""
hasher = hashlib.sha256()
hasher.update(data)
return hasher.hexdigest()
|
negative_train_query273_06690
|
|
matplotlib/setupext.py/_get_ssl_context
def _get_ssl_context():
import certifi
import ssl
return ssl.create_default_context(cafile=certifi.where())
|
negative_train_query273_06691
|
|
matplotlib/setupext.py/get_from_cache_or_download
def get_from_cache_or_download(url, sha):
"""
Get bytes from the given url or local cache.
Parameters
----------
url : str
The url to download.
sha : str
The sha256 of the file.
Returns
-------
BytesIO
The file loaded into memory.
"""
cache_dir = _get_xdg_cache_dir()
if cache_dir is not None: # Try to read from cache.
try:
data = (cache_dir / sha).read_bytes()
except OSError:
pass
else:
if _get_hash(data) == sha:
return BytesIO(data)
# jQueryUI's website blocks direct downloads from urllib.request's
# default User-Agent, but not (for example) wget; so I don't feel too
# bad passing in an empty User-Agent.
with urllib.request.urlopen(
urllib.request.Request(url, headers={"User-Agent": ""}),
context=_get_ssl_context()) as req:
data = req.read()
file_sha = _get_hash(data)
if file_sha != sha:
raise Exception(
f"The downloaded file does not match the expected sha. {url} was "
f"expected to have {sha} but it had {file_sha}")
if cache_dir is not None: # Try to cache the downloaded file.
try:
cache_dir.mkdir(parents=True, exist_ok=True)
with open(cache_dir / sha, "xb") as fout:
fout.write(data)
except OSError:
pass
return BytesIO(data)
|
negative_train_query273_06692
|
|
matplotlib/setupext.py/get_and_extract_tarball
def get_and_extract_tarball(urls, sha, dirname):
"""
Obtain a tarball (from cache or download) and extract it.
Parameters
----------
urls : list[str]
URLs from which download is attempted (in order of attempt), if the
tarball is not in the cache yet.
sha : str
SHA256 hash of the tarball; used both as a cache key (by
`get_from_cache_or_download`) and to validate a downloaded tarball.
dirname : path-like
Directory where the tarball is extracted.
"""
toplevel = Path("build", dirname)
if not toplevel.exists(): # Download it or load it from cache.
try:
import certifi # noqa
except ImportError as e:
raise ImportError(
f"`certifi` is unavailable ({e}) so unable to download any of "
f"the following: {urls}.") from None
Path("build").mkdir(exist_ok=True)
for url in urls:
try:
tar_contents = get_from_cache_or_download(url, sha)
break
except Exception:
pass
else:
raise OSError(
f"Failed to download any of the following: {urls}. "
f"Please download one of these urls and extract it into "
f"'build/' at the top-level of the source repository.")
print(f"Extracting {urllib.parse.urlparse(url).path}")
with tarfile.open(fileobj=tar_contents, mode="r:gz") as tgz:
if os.path.commonpath(tgz.getnames()) != dirname:
raise OSError(
f"The downloaded tgz file was expected to have {dirname} "
f"as sole top-level directory, but that is not the case")
tgz.extractall("build")
return toplevel
|
negative_train_query273_06693
|
|
matplotlib/setupext.py/print_status
def print_status(package, status):
initial_indent = "%12s: " % package
indent = ' ' * 18
print_raw(textwrap.fill(status, width=80,
initial_indent=initial_indent,
subsequent_indent=indent))
|
negative_train_query273_06694
|
|
matplotlib/setupext.py/get_pkg_config
def get_pkg_config():
"""
Get path to pkg-config and set up the PKG_CONFIG environment variable.
"""
if sys.platform == 'win32':
return None
pkg_config = os.environ.get('PKG_CONFIG') or 'pkg-config'
if shutil.which(pkg_config) is None:
print(
"IMPORTANT WARNING:\n"
" pkg-config is not installed.\n"
" Matplotlib may not be able to find some of its dependencies.")
return None
pkg_config_path = sysconfig.get_config_var('LIBDIR')
if pkg_config_path is not None:
pkg_config_path = os.path.join(pkg_config_path, 'pkgconfig')
try:
os.environ['PKG_CONFIG_PATH'] += ':' + pkg_config_path
except KeyError:
os.environ['PKG_CONFIG_PATH'] = pkg_config_path
return pkg_config
|
negative_train_query273_06695
|
|
matplotlib/setupext.py/pkg_config_setup_extension
def pkg_config_setup_extension(
ext, package,
atleast_version=None, alt_exec=None, default_libraries=()):
"""Add parameters to the given *ext* for the given *package*."""
# First, try to get the flags from pkg-config.
pkg_config = get_pkg_config()
cmd = [pkg_config, package] if pkg_config else alt_exec
if cmd is not None:
try:
if pkg_config and atleast_version:
subprocess.check_call(
[*cmd, f"--atleast-version={atleast_version}"])
# Use sys.getfilesystemencoding() to allow round-tripping
# when passed back to later subprocess calls; do not use
# locale.getpreferredencoding() which universal_newlines=True
# would do.
cflags = shlex.split(
os.fsdecode(subprocess.check_output([*cmd, "--cflags"])))
libs = shlex.split(
os.fsdecode(subprocess.check_output([*cmd, "--libs"])))
except (OSError, subprocess.CalledProcessError):
pass
else:
ext.extra_compile_args.extend(cflags)
ext.extra_link_args.extend(libs)
return
# If that fails, fall back on the defaults.
# conda Windows header and library paths.
# https://github.com/conda/conda/issues/2312 re: getting the env dir.
if sys.platform == 'win32':
conda_env_path = (os.getenv('CONDA_PREFIX') # conda >= 4.1
or os.getenv('CONDA_DEFAULT_ENV')) # conda < 4.1
if conda_env_path and os.path.isdir(conda_env_path):
conda_env_path = Path(conda_env_path)
ext.include_dirs.append(str(conda_env_path / "Library/include"))
ext.library_dirs.append(str(conda_env_path / "Library/lib"))
# Default linked libs.
ext.libraries.extend(default_libraries)
|
negative_train_query273_06696
|
|
matplotlib/setupext.py/_pkg_data_helper
def _pkg_data_helper(pkg, subdir):
"""Glob "lib/$pkg/$subdir/**/*", returning paths relative to "lib/$pkg"."""
base = Path("lib", pkg)
return [str(path.relative_to(base)) for path in (base / subdir).rglob("*")]
|
negative_train_query273_06697
|
|
matplotlib/setupext.py/add_numpy_flags
def add_numpy_flags(ext):
import numpy as np
ext.include_dirs.append(np.get_include())
ext.define_macros.extend([
# Ensure that PY_ARRAY_UNIQUE_SYMBOL is uniquely defined for each
# extension.
('PY_ARRAY_UNIQUE_SYMBOL',
'MPL_' + ext.name.replace('.', '_') + '_ARRAY_API'),
('NPY_NO_DEPRECATED_API', 'NPY_1_7_API_VERSION'),
# Allow NumPy's printf format specifiers in C++.
('__STDC_FORMAT_MACROS', 1),
])
|
negative_train_query273_06698
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.