[docs]defallow_rasterization(draw):""" Decorator for Artist.draw method. Provides routines that run before and after the draw call. The before and after functions are useful for changing artist-dependent renderer attributes or making other setup function calls, such as starting and flushing a mixed-mode renderer. """# the axes class has a second argument inframe for its draw method.@wraps(draw)defdraw_wrapper(artist,renderer,*args,**kwargs):try:ifartist.get_rasterized():renderer.start_rasterizing()ifartist.get_agg_filter()isnotNone:renderer.start_filter()returndraw(artist,renderer,*args,**kwargs)finally:ifartist.get_agg_filter()isnotNone:renderer.stop_filter(artist.get_agg_filter())ifartist.get_rasterized():renderer.stop_rasterizing()draw_wrapper._supports_rasterization=Truereturndraw_wrapper

[docs]classArtist(object):""" Abstract base class for objects that render into a FigureCanvas. Typically, all visible elements in a figure are subclasses of Artist. """@cbook.deprecated("3.1")@propertydefaname(self):return'Artist'zorder=0# order of precedence when bulk setting/updating properties# via update. The keys should be property names and the values# integers_prop_order=dict(color=-1)def__init__(self):self._stale=Trueself.stale_callback=Noneself._axes=Noneself.figure=Noneself._transform=Noneself._transformSet=Falseself._visible=Trueself._animated=Falseself._alpha=Noneself.clipbox=Noneself._clippath=Noneself._clipon=Trueself._label=''self._picker=Noneself._contains=Noneself._rasterized=Noneself._agg_filter=Noneself._mouseover=Falseself.eventson=False# fire events only if eventsonself._oid=0# an observer idself._propobservers={}# a dict from oids to funcstry:self.axes=NoneexceptAttributeError:# Handle self.axes as a read-only property, as in Figure.passself._remove_method=Noneself._url=Noneself._gid=Noneself._snap=Noneself._sketch=rcParams['path.sketch']self._path_effects=rcParams['path.effects']self._sticky_edges=_XYPair([],[])self._in_layout=Truedef__getstate__(self):d=self.__dict__.copy()# remove the unpicklable remove method, this will get re-added on load# (by the axes) if the artist lives on an axes.d['stale_callback']=Nonereturnd

[docs]defremove(self):""" Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with `.FigureCanvasBase.draw_idle`. Call `~.axes.Axes.relim` to update the axes limits if desired. Note: `~.axes.Axes.relim` will not see collections even if the collection was added to the axes with *autolim* = True. Note: there is no support for removing the artist's legend entry. """# There is no method to set the callback. Instead the parent should# set the _remove_method attribute directly. This would be a# protected attribute if Python supported that sort of thing. The# callback has one parameter, which is the child to be removed.ifself._remove_methodisnotNone:self._remove_method(self)# clear stale callbackself.stale_callback=None_ax_flag=Falseifhasattr(self,'axes')andself.axes:# remove from the mouse hit listself.axes._mouseover_set.discard(self)# mark the axes as staleself.axes.stale=True# decouple the artist from the axesself.axes=None_ax_flag=Trueifself.figure:self.figure=Noneifnot_ax_flag:self.figure=Trueelse:raiseNotImplementedError('cannot remove artist')

# TODO: the fix for the collections relim problem is to move the# limits calculation into the artist itself, including the property of# whether or not the artist should affect the limits. Then there will# be no distinction between axes.add_line, axes.add_patch, etc.# TODO: add legend support

[docs]defhave_units(self):"""Return *True* if units are set on the *x* or *y* axes."""ax=self.axesifaxisNoneorax.xaxisisNone:returnFalsereturnax.xaxis.have_units()orax.yaxis.have_units()

[docs]defconvert_xunits(self,x):""" Convert *x* using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, *x* itself is returned. """ax=getattr(self,'axes',None)ifaxisNoneorax.xaxisisNone:returnxreturnax.xaxis.convert_units(x)

[docs]defconvert_yunits(self,y):""" Convert *y* using the unit type of the yaxis. If the artist is not in contained in an Axes or if the yaxis does not have units, *y* itself is returned. """ax=getattr(self,'axes',None)ifaxisNoneorax.yaxisisNone:returnyreturnax.yaxis.convert_units(y)

@propertydefaxes(self):"""The `~.axes.Axes` instance the artist resides in, or *None*."""returnself._axes@axes.setterdefaxes(self,new_axes):if(new_axesisnotNoneandself._axesisnotNoneandnew_axes!=self._axes):raiseValueError("Can not reset the axes. You are probably ""trying to re-use an artist in more than one ""Axes which is not supported")self._axes=new_axesifnew_axesisnotNoneandnew_axesisnotself:self.stale_callback=_stale_axes_callbackreturnnew_axes@propertydefstale(self):""" Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist. """returnself._stale@stale.setterdefstale(self,val):self._stale=val# if the artist is animated it does not take normal part in the# draw stack and is not expected to be drawn as part of the normal# draw loop (when not saving) so do not propagate this changeifself.get_animated():returnifvalandself.stale_callbackisnotNone:self.stale_callback(self,val)

[docs]defget_window_extent(self,renderer):""" Get the axes bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly. """returnBbox([[0,0],[0,0]])

[docs]defadd_callback(self,func):""" Add a callback function that will be called whenever one of the `.Artist`'s properties changes. Parameters ---------- func : callable The callback function. It must have the signature:: def func(artist: Artist) -> Any where *artist* is the calling `.Artist`. Return values may exist but are ignored. Returns ------- oid : int The observer id associated with the callback. This id can be used for removing the callback with `.remove_callback` later. See Also -------- remove_callback """oid=self._oidself._propobservers[oid]=funcself._oid+=1returnoid

[docs]defremove_callback(self,oid):""" Remove a callback based on its observer id. See Also -------- add_callback """try:delself._propobservers[oid]exceptKeyError:pass

[docs]defpchanged(self):""" Call all of the registered callbacks. This function is triggered internally when a property is changed. See Also -------- add_callback remove_callback """foroid,funcinself._propobservers.items():func(self)

[docs]defis_transform_set(self):""" Return whether the Artist has an explicitly set transform. This is *True* after `.set_transform` has been called. """returnself._transformSet

[docs]defget_transform(self):"""Return the `.Transform` instance used by this artist."""ifself._transformisNone:self._transform=IdentityTransform()elif(notisinstance(self._transform,Transform)andhasattr(self._transform,'_as_mpl_transform')):self._transform=self._transform._as_mpl_transform(self.axes)returnself._transform

[docs]defget_children(self):r"""Return a list of the child `.Artist`\s of this `.Artist`."""return[]

[docs]defcontains(self,mouseevent):"""Test whether the artist contains the mouse event. Parameters ---------- mouseevent : `matplotlib.backend_bases.MouseEvent` Returns ------- contains : bool Whether any values are within the radius. details : dict An artist-specific dictionary of details of the event context, such as which points are contained in the pick radius. See the individual Artist subclasses for details. See Also -------- set_contains, get_contains """ifself._containsisnotNone:returnself._contains(self,mouseevent)_log.warning("%r needs 'contains' method",self.__class__.__name__)returnFalse,{}

[docs]defset_contains(self,picker):""" Define a custom contains test for the artist. The provided callable replaces the default `.contains` method of the artist. Parameters ---------- picker : callable A custom picker function to evaluate if an event is within the artist. The function must have the signature:: def contains(artist: Artist, event: MouseEvent) -> bool, dict that returns: - a bool indicating if the event is within the artist - a dict of additional information. The dict should at least return the same information as the default ``contains()`` implementation of the respective artist, but may provide additional information. """ifnotcallable(picker):raiseTypeError("picker is not a callable")self._contains=picker

[docs]defget_contains(self):""" Return the custom contains function of the artist if set, or *None*. See Also -------- set_contains """returnself._contains

[docs]defpick(self,mouseevent):""" Process a pick event. Each child artist will fire a pick event if *mouseevent* is over the artist and the artist has picker set. See Also -------- set_picker, get_picker, pickable """# Pick selfifself.pickable():picker=self.get_picker()ifcallable(picker):inside,prop=picker(self,mouseevent)else:inside,prop=self.contains(mouseevent)ifinside:self.figure.canvas.pick_event(mouseevent,self,**prop)# Pick childrenforainself.get_children():# make sure the event happened in the same axesax=getattr(a,'axes',None)if(mouseevent.inaxesisNoneoraxisNoneormouseevent.inaxes==ax):# we need to check if mouseevent.inaxes is None# because some objects associated with an axes (e.g., a# tick label) can be outside the bounding box of the# axes and inaxes will be None# also check that ax is None so that it traverse objects# which do no have an axes property but children mighta.pick(mouseevent)

[docs]defset_picker(self,picker):""" Define the picking behavior of the artist. Parameters ---------- picker : None or bool or float or callable This can be one of the following: - *None*: Picking is disabled for this artist (default). - A boolean: If *True* then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. - A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if it's data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event - A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event:: hit, props = picker(artist, mouseevent) to determine the hit test. if the mouse event is over the artist, return *hit=True* and props is a dictionary of properties you want added to the PickEvent attributes. """self._picker=picker

[docs]defget_picker(self):""" Return the picking behavior of the artist. The possible values are described in `.set_picker`. See Also -------- set_picker, pickable, pick """returnself._picker

[docs]defget_snap(self):""" Returns the snap setting. See `.set_snap` for details. """ifrcParams['path.snap']:returnself._snapelse:returnFalse

[docs]defset_snap(self,snap):""" Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters ---------- snap : bool or None Possible values: - *True*: Snap vertices to the nearest pixel center. - *False*: Do not modify vertex positions. - *None*: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center. """self._snap=snapself.stale=True

[docs]defget_sketch_params(self):""" Returns the sketch parameters for the artist. Returns ------- sketch_params : tuple or None A 3-tuple with the following elements: - *scale*: The amplitude of the wiggle perpendicular to the source line. - *length*: The length of the wiggle along the line. - *randomness*: The scale factor by which the length is shrunken or expanded. Returns *None* if no sketch parameters were set. """returnself._sketch

[docs]defset_sketch_params(self,scale=None,length=None,randomness=None):""" Sets the sketch parameters. Parameters ---------- scale : float, optional The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is `None`, or not provided, no sketch filter will be provided. length : float, optional The length of the wiggle along the line, in pixels (default 128.0) randomness : float, optional The scale factor by which the length is shrunken or expanded (default 16.0) .. ACCEPTS: (scale: float, length: float, randomness: float) """ifscaleisNone:self._sketch=Noneelse:self._sketch=(scale,lengthor128.0,randomnessor16.0)self.stale=True

[docs]defset_figure(self,fig):""" Set the `.Figure` instance the artist belongs to. Parameters ---------- fig : `.Figure` """# if this is a no-op just returnifself.figureisfig:return# if we currently have a figure (the case of both `self.figure`# and `fig` being none is taken care of above) we then user is# trying to change the figure an artist is associated with which# is not allowed for the same reason as adding the same instance# to more than one Axesifself.figureisnotNone:raiseRuntimeError("Can not put single artist in ""more than one figure")self.figure=figifself.figureandself.figureisnotself:self.pchanged()self.stale=True

[docs]defset_clip_path(self,path,transform=None):""" Set the artist's clip path, which may be: - a :class:`~matplotlib.patches.Patch` (or subclass) instance; or - a :class:`~matplotlib.path.Path` instance, in which case a :class:`~matplotlib.transforms.Transform` instance, which will be applied to the path before using it for clipping, must be provided; or - ``None``, to remove a previously set clipping path. For efficiency, if the path happens to be an axis-aligned rectangle, this method will set the clipping box to the corresponding rectangle and set the clipping path to ``None``. ACCEPTS: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None] """frommatplotlib.patchesimportPatch,Rectanglesuccess=FalseiftransformisNone:ifisinstance(path,Rectangle):self.clipbox=TransformedBbox(Bbox.unit(),path.get_transform())self._clippath=Nonesuccess=Trueelifisinstance(path,Patch):self._clippath=TransformedPatchPath(path)success=Trueelifisinstance(path,tuple):path,transform=pathifpathisNone:self._clippath=Nonesuccess=Trueelifisinstance(path,Path):self._clippath=TransformedPath(path,transform)success=Trueelifisinstance(path,TransformedPatchPath):self._clippath=pathsuccess=Trueelifisinstance(path,TransformedPath):self._clippath=pathsuccess=Trueifnotsuccess:raiseTypeError("Invalid arguments to set_clip_path, of type {} and {}".format(type(path).__name__,type(transform).__name__))# This may result in the callbacks being hit twice, but guarantees they# will be hit at least once.self.pchanged()self.stale=True

[docs]defget_alpha(self):""" Return the alpha value used for blending - not supported on all backends """returnself._alpha

[docs]defget_visible(self):"""Return the visibility."""returnself._visible

[docs]defget_transformed_clip_path_and_affine(self):''' Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation. '''ifself._clippathisnotNone:returnself._clippath.get_transformed_path_and_affine()returnNone,None

[docs]defset_clip_on(self,b):""" Set whether the artist uses clipping. When False artists will be visible out side of the axes which can lead to unexpected results. Parameters ---------- b : bool """self._clipon=b# This may result in the callbacks being hit twice, but ensures they# are hit at least onceself.pchanged()self.stale=True

def_set_gc_clip(self,gc):'Set the clip properly for the gc'ifself._clipon:ifself.clipboxisnotNone:gc.set_clip_rectangle(self.clipbox)gc.set_clip_path(self._clippath)else:gc.set_clip_rectangle(None)gc.set_clip_path(None)

[docs]defget_rasterized(self):"""Return whether the artist is to be rasterized."""returnself._rasterized

[docs]defdraw(self,renderer,*args,**kwargs):""" Draw the Artist using the given renderer. This method will be overridden in the Artist subclasses. Typically, it is implemented to not have any effect if the Artist is not visible (`.Artist.get_visible` is *False*). Parameters ---------- renderer : `.RendererBase` subclass. """ifnotself.get_visible():returnself.stale=False

[docs]defset_alpha(self,alpha):""" Set the alpha value used for blending - not supported on all backends. Parameters ---------- alpha : float """self._alpha=alphaself.pchanged()self.stale=True

[docs]defset_in_layout(self,in_layout):""" Set if artist is to be included in layout calculations, E.g. :doc:`/tutorials/intermediate/constrainedlayout_guide`, `.Figure.tight_layout()`, and ``fig.savefig(fname, bbox_inches='tight')``. Parameters ---------- in_layout : bool """self._in_layout=in_layout

[docs]defupdate(self,props):""" Update this artist's properties from the dictionary *props*. """def_update_property(self,k,v):"""Sorting out how to update property (setter or setattr). Parameters ---------- k : str The name of property to update v : obj The value to assign to the property Returns ------- ret : obj or None If using a `set_*` method return it's return, else None. """k=k.lower()# white list attributes we want to be able to update through# art.update, art.set, setpifkin{'axes'}:returnsetattr(self,k,v)else:func=getattr(self,'set_'+k,None)ifnotcallable(func):raiseAttributeError('{!r} object has no property {!r}'.format(type(self).__name__,k))returnfunc(v)withcbook._setattr_cm(self,eventson=False):ret=[_update_property(self,k,v)fork,vinprops.items()]iflen(ret):self.pchanged()self.stale=Truereturnret

[docs]defget_label(self):"""Return the label used for this artist in the legend."""returnself._label

[docs]defset_label(self,s):""" Set a label that will be displayed in the legend. Parameters ---------- s : object *s* will be converted to a string by calling `str`. """ifsisnotNone:self._label=str(s)else:self._label=Noneself.pchanged()self.stale=True

@propertydefsticky_edges(self):""" ``x`` and ``y`` sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. This attribute cannot be assigned to; however, the ``x`` and ``y`` lists can be modified in place as needed. Examples -------- >>> artist.sticky_edges.x[:] = (xmin, xmax) >>> artist.sticky_edges.y[:] = (ymin, ymax) """returnself._sticky_edges

[docs]defupdate_from(self,other):'Copy properties from *other* to *self*.'self._transform=other._transformself._transformSet=other._transformSetself._visible=other._visibleself._alpha=other._alphaself.clipbox=other.clipboxself._clipon=other._cliponself._clippath=other._clippathself._label=other._labelself._sketch=other._sketchself._path_effects=other._path_effectsself.sticky_edges.x[:]=other.sticky_edges.x[:]self.sticky_edges.y[:]=other.sticky_edges.y[:]self.pchanged()self.stale=True

[docs]defproperties(self):"""Return a dictionary of all the properties of the artist."""returnArtistInspector(self).properties()

[docs]deffindobj(self,match=None,include_self=True):""" Find artist objects. Recursively find all `.Artist` instances contained in the artist. Parameters ---------- match A filter criterion for the matches. This can be - *None*: Return all objects contained in artist. - A function with signature ``def match(artist: Artist) -> bool``. The result will only contain artists for which the function returns *True*. - A class instance: e.g., `.Line2D`. The result will only contain artists of this class or its subclasses (``isinstance`` check). include_self : bool Include *self* in the list to be checked for a match. Returns ------- artists : list of `.Artist` """ifmatchisNone:# always return Truedefmatchfunc(x):returnTrueelifisinstance(match,type)andissubclass(match,Artist):defmatchfunc(x):returnisinstance(x,match)elifcallable(match):matchfunc=matchelse:raiseValueError('match must be None, a matplotlib.artist.Artist ''subclass, or a callable')artists=sum([c.findobj(matchfunc)forcinself.get_children()],[])ifinclude_selfandmatchfunc(self):artists.append(self)returnartists

[docs]defget_cursor_data(self,event):""" Return the cursor data for a given event. .. note:: This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns *None*. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that `.format_cursor_data` can convert the data to a string representation. The only current use case is displaying the z-value of an `.AxesImage` in the status bar of a plot window, while moving the mouse. Parameters ---------- event : `matplotlib.backend_bases.MouseEvent` See Also -------- format_cursor_data """returnNone

[docs]defformat_cursor_data(self,data):""" Return a string representation of *data*. .. note:: This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets. See Also -------- get_cursor_data """try:data[0]except(TypeError,IndexError):data=[data]data_str=', '.join('{:0.3g}'.format(item)foritemindataifisinstance(item,Number))return"["+data_str+"]"

[docs]classArtistInspector(object):""" A helper class to inspect an `~matplotlib.artist.Artist` and return information about its settable properties and their current values. """

[docs]def__init__(self,o):r""" Initialize the artist inspector with an `Artist` or an iterable of `Artist`\s. If an iterable is used, we assume it is a homogeneous sequence (all `Artists` are of the same type) and it is your responsibility to make sure this is so. """ifnotisinstance(o,Artist):ifnp.iterable(o):o=list(o)iflen(o):o=o[0]self.oorig=oifnotisinstance(o,type):o=type(o)self.o=oself.aliasd=self.get_aliases()

[docs]defget_aliases(self):""" Get a dict mapping property fullnames to sets of aliases for each alias in the :class:`~matplotlib.artist.ArtistInspector`. e.g., for lines:: {'markerfacecolor': {'mfc'}, 'linewidth' : {'lw'}, } """names=[namefornameindir(self.o)ifname.startswith(('set_','get_'))andcallable(getattr(self.o,name))]aliases={}fornameinnames:func=getattr(self.o,name)ifnotself.is_alias(func):continuepropname=re.search("`({}.*)`".format(name[:4]),# get_.*/set_.*inspect.getdoc(func)).group(1)aliases.setdefault(propname[4:],set()).add(name[4:])returnaliases

[docs]defget_valid_values(self,attr):""" Get the legal arguments for the setter associated with *attr*. This is done by querying the docstring of the setter for a line that begins with "ACCEPTS:" or ".. ACCEPTS:", and then by looking for a numpydoc-style documentation for the setter's first argument. """name='set_%s'%attrifnothasattr(self.o,name):raiseAttributeError('%s has no function %s'%(self.o,name))func=getattr(self.o,name)docstring=inspect.getdoc(func)ifdocstringisNone:return'unknown'ifdocstring.startswith('Alias for '):returnNonematch=self._get_valid_values_regex.search(docstring)ifmatchisnotNone:returnre.sub("\n *"," ",match.group(1))# Much faster than list(inspect.signature(func).parameters)[1],# although barely relevant wrt. matplotlib's total import time.param_name=func.__code__.co_varnames[1]# We could set the presence * based on whether the parameter is a# varargs (it can't be a varkwargs) but it's not really worth the it.match=re.search(r"(?m)^ *\*?{} : (.+)".format(param_name),docstring)ifmatch:returnmatch.group(1)return'unknown'

def_get_setters_and_targets(self):""" Get the attribute strings and a full path to where the setter is defined for all setters in an object. """setters=[]fornameindir(self.o):ifnotname.startswith('set_'):continuefunc=getattr(self.o,name)ifnotcallable(func):continuenargs=len(inspect.getfullargspec(func).args)ifnargs<2orself.is_alias(func):continuesource_class=self.o.__module__+"."+self.o.__name__forclsinself.o.mro():ifnameincls.__dict__:source_class=cls.__module__+"."+cls.__name__breaksource_class=self._replace_path(source_class)setters.append((name[4:],source_class+"."+name))returnsettersdef_replace_path(self,source_class):""" Changes the full path to the public API path that is used in sphinx. This is needed for links to work. """replace_dict={'_base._AxesBase':'Axes','_axes.Axes':'Axes'}forkey,valueinreplace_dict.items():source_class=source_class.replace(key,value)returnsource_class

[docs]defget_setters(self):""" Get the attribute strings with setters for object. e.g., for a line, return ``['markerfacecolor', 'linewidth', ....]``. """return[propforprop,targetinself._get_setters_and_targets()]

[docs]defis_alias(self,o):"""Return whether method object *o* is an alias for another method."""ds=inspect.getdoc(o)ifdsisNone:returnFalsereturnds.startswith('Alias for ')

[docs]defaliased_name(self,s):""" Return 'PROPNAME or alias' if *s* has an alias, else return 'PROPNAME'. e.g., for the line markerfacecolor property, which has an alias, return 'markerfacecolor or mfc' and for the transform property, which does not, return 'transform'. """aliases=''.join(' or %s'%xforxinsorted(self.aliasd.get(s,[])))returns+aliases

[docs]defaliased_name_rest(self,s,target):""" Return 'PROPNAME or alias' if *s* has an alias, else return 'PROPNAME', formatted for ReST. e.g., for the line markerfacecolor property, which has an alias, return 'markerfacecolor or mfc' and for the transform property, which does not, return 'transform'. """aliases=''.join(' or %s'%xforxinsorted(self.aliasd.get(s,[])))return':meth:`%s <%s>`%s'%(s,target,aliases)

[docs]defpprint_setters(self,prop=None,leadingspace=2):""" If *prop* is *None*, return a list of strings of all settable properties and their valid values. If *prop* is not *None*, it is a valid property name and that property will be returned as a string of property : valid values. """ifleadingspace:pad=' '*leadingspaceelse:pad=''ifpropisnotNone:accepts=self.get_valid_values(prop)return'%s%s: %s'%(pad,prop,accepts)attrs=self._get_setters_and_targets()attrs.sort()lines=[]forprop,pathinattrs:accepts=self.get_valid_values(prop)name=self.aliased_name(prop)lines.append('%s%s: %s'%(pad,name,accepts))returnlines

[docs]defpprint_setters_rest(self,prop=None,leadingspace=4):""" If *prop* is *None*, return a list of strings of all settable properties and their valid values. Format the output for ReST If *prop* is not *None*, it is a valid property name and that property will be returned as a string of property : valid values. """ifleadingspace:pad=' '*leadingspaceelse:pad=''ifpropisnotNone:accepts=self.get_valid_values(prop)return'%s%s: %s'%(pad,prop,accepts)attrs=sorted(self._get_setters_and_targets())names=[self.aliased_name_rest(prop,target)forprop,targetinattrs]accepts=[self.get_valid_values(prop)forprop,targetinattrs]col0_len=max(len(n)forninnames)col1_len=max(len(a)forainaccepts)table_formatstr=pad+' '+'='*col0_len+' '+'='*col1_lenreturn['',pad+'.. table::',pad+' :class: property-table','',table_formatstr,pad+' '+'Property'.ljust(col0_len)+' '+'Description'.ljust(col1_len),table_formatstr,*[pad+' '+n.ljust(col0_len)+' '+a.ljust(col1_len)forn,ainzip(names,accepts)],table_formatstr,'',]

[docs]defgetp(obj,property=None):""" Return the value of object's property. *property* is an optional string for the property you want to return Example usage:: getp(obj) # get all the object properties getp(obj, 'linestyle') # get the linestyle property *obj* is a :class:`Artist` instance, e.g., :class:`~matplotlib.lines.Line2D` or an instance of a :class:`~matplotlib.axes.Axes` or :class:`matplotlib.text.Text`. If the *property* is 'somename', this function returns obj.get_somename() :func:`getp` can be used to query all the gettable properties with ``getp(obj)``. Many properties have aliases for shorter typing, e.g. 'lw' is an alias for 'linewidth'. In the output, aliases and full property names will be listed as: property or alias = value e.g.: linewidth or lw = 2 """ifpropertyisNone:insp=ArtistInspector(obj)ret=insp.pprint_getters()print('\n'.join(ret))returnfunc=getattr(obj,'get_'+property)returnfunc()

# aliasget=getp

[docs]defsetp(obj,*args,**kwargs):""" Set a property on an artist object. matplotlib supports the use of :func:`setp` ("set property") and :func:`getp` to set and get object properties, as well as to do introspection on the object. For example, to set the linestyle of a line to be dashed, you can do:: >>> line, = plot([1,2,3]) >>> setp(line, linestyle='--') If you want to know the valid types of arguments, you can provide the name of the property you want to set without a value:: >>> setp(line, 'linestyle') linestyle: [ '-' | '--' | '-.' | ':' | 'steps' | 'None' ] If you want to see all the properties that can be set, and their possible values, you can do:: >>> setp(line) ... long output listing omitted You may specify another output file to `setp` if `sys.stdout` is not acceptable for some reason using the `file` keyword-only argument:: >>> with fopen('output.log') as f: >>> setp(line, file=f) :func:`setp` operates on a single instance or a iterable of instances. If you are in query mode introspecting the possible values, only the first instance in the sequence is used. When actually setting values, all the instances will be set. e.g., suppose you have a list of two lines, the following will make both lines thicker and red:: >>> x = arange(0,1.0,0.01) >>> y1 = sin(2*pi*x) >>> y2 = sin(4*pi*x) >>> lines = plot(x, y1, x, y2) >>> setp(lines, linewidth=2, color='r') :func:`setp` works with the MATLAB style string/value pairs or with python kwargs. For example, the following are equivalent:: >>> setp(lines, 'linewidth', 2, 'color', 'r') # MATLAB style >>> setp(lines, linewidth=2, color='r') # python style """ifisinstance(obj,Artist):objs=[obj]else:objs=list(cbook.flatten(obj))ifnotobjs:returninsp=ArtistInspector(objs[0])# file has to be popped before checking if kwargs is emptyprintArgs={}if'file'inkwargs:printArgs['file']=kwargs.pop('file')ifnotkwargsandlen(args)<2:ifargs:print(insp.pprint_setters(prop=args[0]),**printArgs)else:print('\n'.join(insp.pprint_setters()),**printArgs)returniflen(args)%2:raiseValueError('The set args must be string, value pairs')# put args into ordereddict to maintain orderfuncvals=OrderedDict((k,v)fork,vinzip(args[::2],args[1::2]))ret=[o.update(funcvals)foroinobjs]+[o.set(**kwargs)foroinobjs]returnlist(cbook.flatten(ret))

[docs]defkwdoc(artist):r""" Inspect an `~matplotlib.artist.Artist` class (using `.ArtistInspector`) and return information about its settable properties and their current values. Parameters ---------- artist : `~matplotlib.artist.Artist` or an iterable of `Artist`\s Returns ------- string The settable properties of *artist*, as plain text if :rc:`docstring.hardcopy` is False and as a rst table (intended for use in Sphinx) if it is True. """hardcopy=matplotlib.rcParams['docstring.hardcopy']ifhardcopy:return'\n'.join(ArtistInspector(artist).pprint_setters_rest(leadingspace=4))else:return'\n'.join(ArtistInspector(artist).pprint_setters(leadingspace=2))