Dataset Viewer
Auto-converted to Parquet Duplicate
_id
stringlengths
5
9
text
stringlengths
5
385k
title
stringclasses
1 value
doc_0
Return the visibility.
doc_1
Bases: object Stack of elements with a movable cursor. Mimics home/back/forward in a web browser. back()[source] Move the position back and return the current element. bubble(o)[source] Raise all references of o to the top of the stack, and return it. Raises ValueError If o is not in the stack. clear()[source] Empty the stack. empty()[source] Return whether the stack is empty. forward()[source] Move the position forward and return the current element. home()[source] Push the first element onto the top of the stack. The first element is returned. push(o)[source] Push o to the stack at current position. Discard all later elements. o is returned. remove(o)[source] Remove o from the stack. Raises ValueError If o is not in the stack.
doc_2
Base class for figure.Figure and figure.SubFigure containing the methods that add artists to the figure or subfigure, create Axes, etc. add_artist(artist, clip=False)[source] Add an Artist to the figure. Usually artists are added to Axes objects using Axes.add_artist; this method can be used in the rare cases where one needs to add artists directly to the figure instead. Parameters artistArtist The artist to add to the figure. If the added artist has no transform previously set, its transform will be set to figure.transSubfigure. clipbool, default: False Whether the added artist should be clipped by the figure patch. Returns Artist The added artist. add_axes(*args, **kwargs)[source] Add an Axes to the figure. Call signatures: add_axes(rect, projection=None, polar=False, **kwargs) add_axes(ax) Parameters rectsequence of float The dimensions [left, bottom, width, height] of the new Axes. All quantities are in fractions of figure width and height. projection{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional The projection type of the Axes. str is the name of a custom projection, see projections. The default None results in a 'rectilinear' projection. polarbool, default: False If True, equivalent to projection='polar'. axes_classsubclass type of Axes, optional The axes.Axes subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples. sharex, shareyAxes, optional Share the x or y axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes. labelstr A label for the returned Axes. Returns Axes, or a subclass of Axes The returned axes class depends on the projection used. It is Axes if rectilinear projection is used and projections.polar.PolarAxes if polar projection is used. Other Parameters **kwargs This method also takes the keyword arguments for the returned Axes class. The keyword arguments for the rectilinear Axes class Axes can be found in the following table but there might also be other keyword arguments if another projection is used, see the actual Axes class. Property Description adjustable {'box', 'datalim'} agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha scalar or None anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} animated bool aspect {'auto', 'equal'} or float autoscale_on bool autoscalex_on bool autoscaley_on bool axes_locator Callable[[Axes, Renderer], Bbox] axisbelow bool or 'line' box_aspect float or None clip_box Bbox clip_on bool clip_path Patch or (Path, Transform) or None facecolor or fc color figure Figure frame_on bool gid str in_layout bool label object navigate bool navigate_mode unknown path_effects AbstractPathEffect picker None or bool or float or callable position [left, bottom, width, height] or Bbox prop_cycle unknown rasterization_zorder float or None rasterized bool sketch_params (scale: float, length: float, randomness: float) snap bool or None title str transform Transform url str visible bool xbound unknown xlabel str xlim (bottom: float, top: float) xmargin float greater than -0.5 xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase xticklabels unknown xticks unknown ybound unknown ylabel str ylim (bottom: float, top: float) ymargin float greater than -0.5 yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase yticklabels unknown yticks unknown zorder float See also Figure.add_subplot pyplot.subplot pyplot.axes Figure.subplots pyplot.subplots Notes In rare circumstances, add_axes may be called with a single argument, an Axes instance already created in the present figure but not in the figure's list of Axes. Examples Some simple examples: rect = l, b, w, h fig = plt.figure() fig.add_axes(rect) fig.add_axes(rect, frameon=False, facecolor='g') fig.add_axes(rect, polar=True) ax = fig.add_axes(rect, projection='polar') fig.delaxes(ax) fig.add_axes(ax) add_callback(func)[source] Add a callback function that will be called whenever one of the Artist's properties changes. Parameters funccallable 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 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 add_gridspec(nrows=1, ncols=1, **kwargs)[source] Return a GridSpec that has this figure as a parent. This allows complex layout of Axes in the figure. Parameters nrowsint, default: 1 Number of rows in grid. ncolsint, default: 1 Number or columns in grid. Returns GridSpec Other Parameters **kwargs Keyword arguments are passed to GridSpec. See also matplotlib.pyplot.subplots Examples Adding a subplot that spans two rows: fig = plt.figure() gs = fig.add_gridspec(2, 2) ax1 = fig.add_subplot(gs[0, 0]) ax2 = fig.add_subplot(gs[1, 0]) # spans two rows: ax3 = fig.add_subplot(gs[:, 1]) add_subfigure(subplotspec, **kwargs)[source] Add a SubFigure to the figure as part of a subplot arrangement. Parameters subplotspecgridspec.SubplotSpec Defines the region in a parent gridspec where the subfigure will be placed. Returns figure.SubFigure Other Parameters **kwargs Are passed to the SubFigure object. See also Figure.subfigures add_subplot(*args, **kwargs)[source] Add an Axes to the figure as part of a subplot arrangement. Call signatures: add_subplot(nrows, ncols, index, **kwargs) add_subplot(pos, **kwargs) add_subplot(ax) add_subplot() Parameters *argsint, (int, int, index), or SubplotSpec, default: (1, 1, 1) The position of the subplot described by one of Three integers (nrows, ncols, index). The subplot will take the index position on a grid with nrows rows and ncols columns. index starts at 1 in the upper left corner and increases to the right. index can also be a two-tuple specifying the (first, last) indices (1-based, and including last) of the subplot, e.g., fig.add_subplot(3, 1, (1, 2)) makes a subplot that spans the upper 2/3 of the figure. A 3-digit integer. The digits are interpreted as if given separately as three single-digit integers, i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that this can only be used if there are no more than 9 subplots. A SubplotSpec. In rare circumstances, add_subplot may be called with a single argument, a subplot Axes instance already created in the present figure but not in the figure's list of Axes. projection{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional The projection type of the subplot (Axes). str is the name of a custom projection, see projections. The default None results in a 'rectilinear' projection. polarbool, default: False If True, equivalent to projection='polar'. axes_classsubclass type of Axes, optional The axes.Axes subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples. sharex, shareyAxes, optional Share the x or y axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes. labelstr A label for the returned Axes. Returns axes.SubplotBase, or another subclass of Axes The Axes of the subplot. The returned Axes base class depends on the projection used. It is Axes if rectilinear projection is used and projections.polar.PolarAxes if polar projection is used. The returned Axes is then a subplot subclass of the base class. Other Parameters **kwargs This method also takes the keyword arguments for the returned Axes base class; except for the figure argument. The keyword arguments for the rectilinear base class Axes can be found in the following table but there might also be other keyword arguments if another projection is used. Property Description adjustable {'box', 'datalim'} agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha scalar or None anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} animated bool aspect {'auto', 'equal'} or float autoscale_on bool autoscalex_on bool autoscaley_on bool axes_locator Callable[[Axes, Renderer], Bbox] axisbelow bool or 'line' box_aspect float or None clip_box Bbox clip_on bool clip_path Patch or (Path, Transform) or None facecolor or fc color figure Figure frame_on bool gid str in_layout bool label object navigate bool navigate_mode unknown path_effects AbstractPathEffect picker None or bool or float or callable position [left, bottom, width, height] or Bbox prop_cycle unknown rasterization_zorder float or None rasterized bool sketch_params (scale: float, length: float, randomness: float) snap bool or None title str transform Transform url str visible bool xbound unknown xlabel str xlim (bottom: float, top: float) xmargin float greater than -0.5 xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase xticklabels unknown xticks unknown ybound unknown ylabel str ylim (bottom: float, top: float) ymargin float greater than -0.5 yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase yticklabels unknown yticks unknown zorder float See also Figure.add_axes pyplot.subplot pyplot.axes Figure.subplots pyplot.subplots Examples fig = plt.figure() fig.add_subplot(231) ax1 = fig.add_subplot(2, 3, 1) # equivalent but more general fig.add_subplot(232, frameon=False) # subplot with no frame fig.add_subplot(233, projection='polar') # polar subplot fig.add_subplot(234, sharex=ax1) # subplot sharing x-axis with ax1 fig.add_subplot(235, facecolor="red") # red subplot ax1.remove() # delete ax1 from the figure fig.add_subplot(ax1) # add ax1 back to the figure align_labels(axs=None)[source] Align the xlabels and ylabels of subplots with the same subplots row or column (respectively) if label alignment is being done automatically (i.e. the label position is not manually set). Alignment persists for draw events after this is called. Parameters axslist of Axes Optional list (or ndarray) of Axes to align the labels. Default is to align all Axes on the figure. See also matplotlib.figure.Figure.align_xlabels matplotlib.figure.Figure.align_ylabels align_xlabels(axs=None)[source] Align the xlabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set). Alignment persists for draw events after this is called. If a label is on the bottom, it is aligned with labels on Axes that also have their label on the bottom and that have the same bottom-most subplot row. If the label is on the top, it is aligned with labels on Axes with the same top-most row. Parameters axslist of Axes Optional list of (or ndarray) Axes to align the xlabels. Default is to align all Axes on the figure. See also matplotlib.figure.Figure.align_ylabels matplotlib.figure.Figure.align_labels Notes This assumes that axs are from the same GridSpec, so that their SubplotSpec positions correspond to figure positions. Examples Example with rotated xtick labels: fig, axs = plt.subplots(1, 2) for tick in axs[0].get_xticklabels(): tick.set_rotation(55) axs[0].set_xlabel('XLabel 0') axs[1].set_xlabel('XLabel 1') fig.align_xlabels() align_ylabels(axs=None)[source] Align the ylabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set). Alignment persists for draw events after this is called. If a label is on the left, it is aligned with labels on Axes that also have their label on the left and that have the same left-most subplot column. If the label is on the right, it is aligned with labels on Axes with the same right-most column. Parameters axslist of Axes Optional list (or ndarray) of Axes to align the ylabels. Default is to align all Axes on the figure. See also matplotlib.figure.Figure.align_xlabels matplotlib.figure.Figure.align_labels Notes This assumes that axs are from the same GridSpec, so that their SubplotSpec positions correspond to figure positions. Examples Example with large yticks labels: fig, axs = plt.subplots(2, 1) axs[0].plot(np.arange(0, 1000, 50)) axs[0].set_ylabel('YLabel 0') axs[1].set_ylabel('YLabel 1') fig.align_ylabels() autofmt_xdate(bottom=0.2, rotation=30, ha='right', which='major')[source] Date ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared x-axis where the x-axis is date data. The ticklabels are often long, and it helps to rotate them on the bottom subplot and turn them off on other subplots, as well as turn off xlabels. Parameters bottomfloat, default: 0.2 The bottom of the subplots for subplots_adjust. rotationfloat, default: 30 degrees The rotation angle of the xtick labels in degrees. ha{'left', 'center', 'right'}, default: 'right' The horizontal alignment of the xticklabels. which{'major', 'minor', 'both'}, default: 'major' Selects which ticklabels to rotate. propertyaxes The Axes instance the artist resides in, or None. colorbar(mappable, cax=None, ax=None, use_gridspec=True, **kw)[source] Add a colorbar to a plot. Parameters mappable The matplotlib.cm.ScalarMappable (i.e., AxesImage, ContourSet, etc.) described by this colorbar. This argument is mandatory for the Figure.colorbar method but optional for the pyplot.colorbar function, which sets the default to the current image. Note that one can create a ScalarMappable "on-the-fly" to generate colorbars not attached to a previously drawn artist, e.g. fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax) caxAxes, optional Axes into which the colorbar will be drawn. axAxes, list of Axes, optional One or more parent axes from which space for a new colorbar axes will be stolen, if cax is None. This has no effect if cax is set. use_gridspecbool, optional If cax is None, a new cax is created as an instance of Axes. If ax is an instance of Subplot and use_gridspec is True, cax is created as an instance of Subplot using the gridspec module. Returns colorbarColorbar Notes Additional keyword arguments are of two kinds: axes properties: locationNone or {'left', 'right', 'top', 'bottom'} The location, relative to the parent axes, where the colorbar axes is created. It also determines the orientation of the colorbar (colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal). If None, the location will come from the orientation if it is set (vertical colorbars on the right, horizontal ones at the bottom), or default to 'right' if orientation is unset. orientationNone or {'vertical', 'horizontal'} The orientation of the colorbar. It is preferable to set the location of the colorbar, as that also determines the orientation; passing incompatible values for location and orientation raises an exception. fractionfloat, default: 0.15 Fraction of original axes to use for colorbar. shrinkfloat, default: 1.0 Fraction by which to multiply the size of the colorbar. aspectfloat, default: 20 Ratio of long to short dimensions. padfloat, default: 0.05 if vertical, 0.15 if horizontal Fraction of original axes between colorbar and new image axes. anchor(float, float), optional The anchor point of the colorbar axes. Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal. panchor(float, float), or False, optional The anchor point of the colorbar parent axes. If False, the parent axes' anchor will be unchanged. Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal. colorbar properties: Property Description extend {'neither', 'both', 'min', 'max'} If not 'neither', make pointed end(s) for out-of- range values. These are set for a given colormap using the colormap set_under and set_over methods. extendfrac {None, 'auto', length, lengths} If set to None, both the minimum and maximum triangular colorbar extensions with have a length of 5% of the interior colorbar length (this is the default setting). If set to 'auto', makes the triangular colorbar extensions the same lengths as the interior boxes (when spacing is set to 'uniform') or the same lengths as the respective adjacent interior boxes (when spacing is set to 'proportional'). If a scalar, indicates the length of both the minimum and maximum triangular colorbar extensions as a fraction of the interior colorbar length. A two-element sequence of fractions may also be given, indicating the lengths of the minimum and maximum colorbar extensions respectively as a fraction of the interior colorbar length. extendrect bool If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular. spacing {'uniform', 'proportional'} Uniform spacing gives each discrete color the same space; proportional makes the space proportional to the data interval. ticks None or list of ticks or Locator If None, ticks are determined automatically from the input. format None or str or Formatter If None, ScalarFormatter is used. If a format string is given, e.g., '%.3f', that is used. An alternative Formatter may be given instead. drawedges bool Whether to draw lines at color boundaries. label str The label on the colorbar's long axis. The following will probably be useful only in the context of indexed colors (that is, when the mappable has norm=NoNorm()), or other unusual circumstances. Property Description boundaries None or a sequence values None or a sequence which must be of length 1 less than the sequence of boundaries. For each region delimited by adjacent entries in boundaries, the colormapped to the corresponding value in values will be used. If mappable is a ContourSet, its extend kwarg is included automatically. The shrink kwarg provides a simple way to scale the colorbar with respect to the axes. Note that if cax is specified, it determines the size of the colorbar and shrink and aspect kwargs are ignored. For more precise control, you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn. In this case, do not use any of the axes properties kwargs. It is known that some vector graphics viewers (svg and pdf) renders white gaps between segments of the colorbar. This is due to bugs in the viewers, not Matplotlib. As a workaround, the colorbar can be rendered with overlapping segments: cbar = colorbar() cbar.solids.set_edgecolor("face") draw() However this has negative consequences in other circumstances, e.g. with semi-transparent images (alpha < 1) and colorbar extensions; therefore, this workaround is not used by default (see issue #1188). contains(mouseevent)[source] Test whether the mouse event occurred on the figure. Returns bool, {} convert_xunits(x)[source] 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. convert_yunits(y)[source] 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. delaxes(ax)[source] Remove the Axes ax from the figure; update the current Axes. draw(renderer)[source] Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters rendererRendererBase subclass. Notes This method is overridden in the Artist subclasses. findobj(match=None, include_self=True)[source] 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_selfbool Include self in the list to be checked for a match. Returns list of Artist format_cursor_data(data)[source] 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, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter. See also get_cursor_data propertyframeon Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible(). gca(**kwargs)[source] Get the current Axes. If there is currently no Axes on this Figure, a new one is created using Figure.add_subplot. (To test whether there is currently an Axes on a Figure, check whether figure.axes is empty. To test whether there is currently a Figure on the pyplot figure stack, check whether pyplot.get_fignums() is empty.) The following kwargs are supported for ensuring the returned Axes adheres to the given projection etc., and for Axes creation if the active Axes does not exist: Property Description adjustable {'box', 'datalim'} agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha scalar or None anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} animated bool aspect {'auto', 'equal'} or float autoscale_on bool autoscalex_on bool autoscaley_on bool axes_locator Callable[[Axes, Renderer], Bbox] axisbelow bool or 'line' box_aspect float or None clip_box Bbox clip_on bool clip_path Patch or (Path, Transform) or None facecolor or fc color figure Figure frame_on bool gid str in_layout bool label object navigate bool navigate_mode unknown path_effects AbstractPathEffect picker None or bool or float or callable position [left, bottom, width, height] or Bbox prop_cycle unknown rasterization_zorder float or None rasterized bool sketch_params (scale: float, length: float, randomness: float) snap bool or None title str transform Transform url str visible bool xbound unknown xlabel str xlim (bottom: float, top: float) xmargin float greater than -0.5 xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase xticklabels unknown xticks unknown ybound unknown ylabel str ylim (bottom: float, top: float) ymargin float greater than -0.5 yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase yticklabels unknown yticks unknown zorder float get_agg_filter()[source] Return filter function to be used for agg filter. get_alpha()[source] Return the alpha value used for blending - not supported on all backends. get_animated()[source] Return whether the artist is animated. get_children()[source] Get a list of artists contained in the figure. get_clip_box()[source] Return the clipbox. get_clip_on()[source] Return whether the artist uses clipping. get_clip_path()[source] Return the clip path. get_cursor_data(event)[source] 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 eventmatplotlib.backend_bases.MouseEvent See also format_cursor_data get_default_bbox_extra_artists()[source] get_edgecolor()[source] Get the edge color of the Figure rectangle. get_facecolor()[source] Get the face color of the Figure rectangle. get_figure()[source] Return the Figure instance the artist belongs to. get_frameon()[source] Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible(). get_gid()[source] Return the group id. get_in_layout()[source] Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). get_label()[source] Return the label used for this artist in the legend. get_linewidth()[source] Get the line width of the Figure rectangle. get_path_effects()[source] get_picker()[source] Return the picking behavior of the artist. The possible values are described in set_picker. See also set_picker, pickable, pick get_rasterized()[source] Return whether the artist is to be rasterized. get_sketch_params()[source] Return the sketch parameters for the artist. Returns 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. get_snap()[source] Return the snap setting. See set_snap for details. get_tightbbox(renderer, bbox_extra_artists=None)[source] Return a (tight) bounding box of the figure in inches. Note that FigureBase differs from all other artists, which return their Bbox in pixels. Artists that have artist.set_in_layout(False) are not included in the bbox. Parameters rendererRendererBase subclass renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()) bbox_extra_artistslist of Artist or None List of artists to include in the tight bounding box. If None (default), then all artist children of each Axes are included in the tight bounding box. Returns BboxBase containing the bounding box (in figure inches). get_transform()[source] Return the Transform instance used by this artist. get_transformed_clip_path_and_affine()[source] Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation. get_url()[source] Return the url. get_visible()[source] Return the visibility. get_window_extent(*args, **kwargs)[source] Get the artist's 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. get_zorder()[source] Return the artist's zorder. have_units()[source] Return whether units are set on any axis. is_transform_set()[source] Return whether the Artist has an explicitly set transform. This is True after set_transform has been called. legend(*args, **kwargs)[source] Place a legend on the figure. Call signatures: legend() legend(handles, labels) legend(handles=handles) legend(labels) The call signatures correspond to the following different ways to use this method: 1. Automatic detection of elements to be shown in the legend The elements to be added to the legend are automatically determined, when you do not pass in any extra arguments. In this case, the labels are taken from the artist. You can specify them either at artist creation or by calling the set_label() method on the artist: ax.plot([1, 2, 3], label='Inline label') fig.legend() or: line, = ax.plot([1, 2, 3]) line.set_label('Label via method') fig.legend() Specific lines can be excluded from the automatic legend element selection by defining a label starting with an underscore. This is default for all artists, so calling Figure.legend without any arguments and without setting the labels manually will result in no legend being drawn. 2. Explicitly listing the artists and labels in the legend For full control of which artists have a legend entry, it is possible to pass an iterable of legend artists followed by an iterable of legend labels respectively: fig.legend([line1, line2, line3], ['label1', 'label2', 'label3']) 3. Explicitly listing the artists in the legend This is similar to 2, but the labels are taken from the artists' label properties. Example: line1, = ax1.plot([1, 2, 3], label='label1') line2, = ax2.plot([1, 2, 3], label='label2') fig.legend(handles=[line1, line2]) 4. Labeling existing plot elements Discouraged This call signature is discouraged, because the relation between plot elements and labels is only implicit by their order and can easily be mixed up. To make a legend for all artists on all Axes, call this function with an iterable of strings, one for each legend item. For example: fig, (ax1, ax2) = plt.subplots(1, 2) ax1.plot([1, 3, 5], color='blue') ax2.plot([2, 4, 6], color='red') fig.legend(['the blues', 'the reds']) Parameters handleslist of Artist, optional A list of Artists (lines, patches) to be added to the legend. Use this together with labels, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient. The length of handles and labels should be the same in this case. If they are not, they are truncated to the smaller length. labelslist of str, optional A list of labels to show next to the artists. Use this together with handles, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient. Returns Legend Other Parameters locstr or pair of floats, default: rcParams["legend.loc"] (default: 'best') ('best' for axes, 'upper right' for figures) The location of the legend. The strings 'upper left', 'upper right', 'lower left', 'lower right' place the legend at the corresponding corner of the axes/figure. The strings 'upper center', 'lower center', 'center left', 'center right' place the legend at the center of the corresponding edge of the axes/figure. The string 'center' places the legend at the center of the axes/figure. The string 'best' places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists. This option can be quite slow for plots with large amounts of data; your plotting speed may benefit from providing a specific location. The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored). For back-compatibility, 'center right' (but no other location) can also be spelled 'right', and each "string" locations can also be given as a numeric value: Location String Location Code 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 bbox_to_anchorBboxBase, 2-tuple, or 4-tuple of floats Box that is used to position the legend in conjunction with loc. Defaults to axes.bbox (if called as a method to Axes.legend) or figure.bbox (if Figure.legend). This argument allows arbitrary placement of the legend. Bbox coordinates are interpreted in the coordinate system given by bbox_transform, with the default transform Axes or Figure coordinates, depending on which legend is called. If a 4-tuple or BboxBase is given, then it specifies the bbox (x, y, width, height) that the legend is placed in. To put the legend in the best location in the bottom right quadrant of the axes (or figure): loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5) A 2-tuple (x, y) places the corner of the legend specified by loc at x, y. For example, to put the legend's upper right-hand corner in the center of the axes (or figure) the following keywords can be used: loc='upper right', bbox_to_anchor=(0.5, 0.5) ncolint, default: 1 The number of columns that the legend has. propNone or matplotlib.font_manager.FontProperties or dict The font properties of the legend. If None (default), the current matplotlib.rcParams will be used. fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'} The font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if prop is not specified. labelcolorstr or list, default: rcParams["legend.labelcolor"] (default: 'None') The color of the text in the legend. Either a valid color string (for example, 'red'), or a list of color strings. The labelcolor can also be made to match the color of the line or marker using 'linecolor', 'markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec'). Labelcolor can be set globally using rcParams["legend.labelcolor"] (default: 'None'). If None, use rcParams["text.color"] (default: 'black'). numpointsint, default: rcParams["legend.numpoints"] (default: 1) The number of marker points in the legend when creating a legend entry for a Line2D (line). scatterpointsint, default: rcParams["legend.scatterpoints"] (default: 1) The number of marker points in the legend when creating a legend entry for a PathCollection (scatter plot). scatteryoffsetsiterable of floats, default: [0.375, 0.5, 0.3125] The vertical offset (relative to the font size) for the markers created for a scatter plot legend entry. 0.0 is at the base the legend text, and 1.0 is at the top. To draw all markers at the same height, set to [0.5]. markerscalefloat, default: rcParams["legend.markerscale"] (default: 1.0) The relative size of legend markers compared with the originally drawn ones. markerfirstbool, default: True If True, legend marker is placed to the left of the legend label. If False, legend marker is placed to the right of the legend label. frameonbool, default: rcParams["legend.frameon"] (default: True) Whether the legend should be drawn on a patch (frame). fancyboxbool, default: rcParams["legend.fancybox"] (default: True) Whether round edges should be enabled around the FancyBboxPatch which makes up the legend's background. shadowbool, default: rcParams["legend.shadow"] (default: False) Whether to draw a shadow behind the legend. framealphafloat, default: rcParams["legend.framealpha"] (default: 0.8) The alpha transparency of the legend's background. If shadow is activated and framealpha is None, the default value is ignored. facecolor"inherit" or color, default: rcParams["legend.facecolor"] (default: 'inherit') The legend's background color. If "inherit", use rcParams["axes.facecolor"] (default: 'white'). edgecolor"inherit" or color, default: rcParams["legend.edgecolor"] (default: '0.8') The legend's background patch edge color. If "inherit", use take rcParams["axes.edgecolor"] (default: 'black'). mode{"expand", None} If mode is set to "expand" the legend will be horizontally expanded to fill the axes area (or bbox_to_anchor if defines the legend's size). bbox_transformNone or matplotlib.transforms.Transform The transform for the bounding box (bbox_to_anchor). For a value of None (default) the Axes' transAxes transform will be used. titlestr or None The legend's title. Default is no title (None). title_fontpropertiesNone or matplotlib.font_manager.FontProperties or dict The font properties of the legend's title. If None (default), the title_fontsize argument will be used if present; if title_fontsize is also None, the current rcParams["legend.title_fontsize"] (default: None) will be used. title_fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}, default: rcParams["legend.title_fontsize"] (default: None) The font size of the legend's title. Note: This cannot be combined with title_fontproperties. If you want to set the fontsize alongside other font properties, use the size parameter in title_fontproperties. borderpadfloat, default: rcParams["legend.borderpad"] (default: 0.4) The fractional whitespace inside the legend border, in font-size units. labelspacingfloat, default: rcParams["legend.labelspacing"] (default: 0.5) The vertical space between the legend entries, in font-size units. handlelengthfloat, default: rcParams["legend.handlelength"] (default: 2.0) The length of the legend handles, in font-size units. handleheightfloat, default: rcParams["legend.handleheight"] (default: 0.7) The height of the legend handles, in font-size units. handletextpadfloat, default: rcParams["legend.handletextpad"] (default: 0.8) The pad between the legend handle and text, in font-size units. borderaxespadfloat, default: rcParams["legend.borderaxespad"] (default: 0.5) The pad between the axes and legend border, in font-size units. columnspacingfloat, default: rcParams["legend.columnspacing"] (default: 2.0) The spacing between columns, in font-size units. handler_mapdict or None The custom dictionary mapping instances or types to a legend handler. This handler_map updates the default handler map found at matplotlib.legend.Legend.get_legend_handler_map. See also Axes.legend Notes Some artists are not supported by this function. See Legend guide for details. propertymouseover If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2. pchanged()[source] Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback remove_callback pick(mouseevent)[source] 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 pickable()[source] Return whether the artist is pickable. See also set_picker, get_picker, pick properties()[source] Return a dictionary of all the properties of the artist. remove()[source] 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 relim to update the axes limits if desired. Note: 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. remove_callback(oid)[source] Remove a callback based on its observer id. See also add_callback sca(a)[source] Set the current Axes to be a and return a. set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, frameon=<UNSET>, gid=<UNSET>, in_layout=<UNSET>, label=<UNSET>, linewidth=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, zorder=<UNSET>)[source] Set multiple properties at once. Supported properties are Property Description agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha scalar or None animated bool clip_box Bbox clip_on bool clip_path Patch or (Path, Transform) or None edgecolor color facecolor color figure Figure frameon bool gid str in_layout bool label object linewidth number path_effects AbstractPathEffect picker None or bool or float or callable rasterized bool sketch_params (scale: float, length: float, randomness: float) snap bool or None transform Transform url str visible bool zorder float set_agg_filter(filter_func)[source] Set the agg filter. Parameters filter_funccallable A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array. set_alpha(alpha)[source] Set the alpha value used for blending - not supported on all backends. Parameters alphascalar or None alpha must be within the 0-1 range, inclusive. set_animated(b)[source] Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters bbool set_clip_box(clipbox)[source] Set the artist's clip Bbox. Parameters clipboxBbox set_clip_on(b)[source] Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters bbool set_clip_path(path, transform=None)[source] Set the artist's clip path. Parameters pathPatch or Path or TransformedPath or None The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed. transformTransform, optional Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter. set_edgecolor(color)[source] Set the edge color of the Figure rectangle. Parameters colorcolor set_facecolor(color)[source] Set the face color of the Figure rectangle. Parameters colorcolor set_figure(fig)[source] Set the Figure instance the artist belongs to. Parameters figFigure set_frameon(b)[source] Set the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.set_visible(). Parameters bbool set_gid(gid)[source] Set the (group) id for the artist. Parameters gidstr set_in_layout(in_layout)[source] Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters in_layoutbool set_label(s)[source] Set a label that will be displayed in the legend. Parameters sobject s will be converted to a string by calling str. set_linewidth(linewidth)[source] Set the line width of the Figure rectangle. Parameters linewidthnumber set_path_effects(path_effects)[source] Set the path effects. Parameters path_effectsAbstractPathEffect set_picker(picker)[source] Define the picking behavior of the artist. Parameters pickerNone 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 its 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. set_rasterized(rasterized)[source] Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters rasterizedbool set_sketch_params(scale=None, length=None, randomness=None)[source] Set the sketch parameters. Parameters scalefloat, 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. lengthfloat, optional The length of the wiggle along the line, in pixels (default 128.0) randomnessfloat, optional The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape. set_snap(snap)[source] 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 snapbool 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. set_transform(t)[source] Set the artist transform. Parameters tTransform set_url(url)[source] Set the url for the artist. Parameters urlstr set_visible(b)[source] Set the artist's visibility. Parameters bbool set_zorder(level)[source] Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters levelfloat propertystale Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist. propertysticky_edges 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. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. 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) subfigures(nrows=1, ncols=1, squeeze=True, wspace=None, hspace=None, width_ratios=None, height_ratios=None, **kwargs)[source] Add a subfigure to this figure or subfigure. A subfigure has the same artist methods as a figure, and is logically the same as a figure, but cannot print itself. See Figure subfigures. Parameters nrows, ncolsint, default: 1 Number of rows/columns of the subfigure grid. squeezebool, default: True If True, extra dimensions are squeezed out from the returned array of subfigures. wspace, hspacefloat, default: None The amount of width/height reserved for space between subfigures, expressed as a fraction of the average subfigure width/height. If not given, the values will be inferred from a figure or rcParams when necessary. width_ratiosarray-like of length ncols, optional Defines the relative widths of the columns. Each column gets a relative width of width_ratios[i] / sum(width_ratios). If not given, all columns will have the same width. height_ratiosarray-like of length nrows, optional Defines the relative heights of the rows. Each row gets a relative height of height_ratios[i] / sum(height_ratios). If not given, all rows will have the same height. subplot_mosaic(mosaic, *, sharex=False, sharey=False, subplot_kw=None, gridspec_kw=None, empty_sentinel='.')[source] Build a layout of Axes based on ASCII art or nested lists. This is a helper function to build complex GridSpec layouts visually. Note This API is provisional and may be revised in the future based on early user feedback. Parameters mosaiclist of list of {hashable or nested} or str A visual layout of how you want your Axes to be arranged labeled as strings. For example x = [['A panel', 'A panel', 'edge'], ['C panel', '.', 'edge']] produces 4 Axes: 'A panel' which is 1 row high and spans the first two columns 'edge' which is 2 rows high and is on the right edge 'C panel' which in 1 row and 1 column wide in the bottom left a blank space 1 row and 1 column wide in the bottom center Any of the entries in the layout can be a list of lists of the same form to create nested layouts. If input is a str, then it can either be a multi-line string of the form ''' AAE C.E ''' where each character is a column and each line is a row. Or it can be a single-line string where rows are separated by ;: 'AB;CC' The string notation allows only single character Axes labels and does not support nesting but is very terse. sharex, shareybool, default: False If True, the x-axis (sharex) or y-axis (sharey) will be shared among all subplots. In that case, tick label visibility and axis units behave as for subplots. If False, each subplot's x- or y-axis will be independent. subplot_kwdict, optional Dictionary with keywords passed to the Figure.add_subplot call used to create each subplot. gridspec_kwdict, optional Dictionary with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on. empty_sentinelobject, optional Entry in the layout to mean "leave this space empty". Defaults to '.'. Note, if layout is a string, it is processed via inspect.cleandoc to remove leading white space, which may interfere with using white-space as the empty sentinel. Returns dict[label, Axes] A dictionary mapping the labels to the Axes objects. The order of the axes is left-to-right and top-to-bottom of their position in the total layout. subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None)[source] Add a set of subplots to this figure. This utility wrapper makes it convenient to create common layouts of subplots in a single call. Parameters nrows, ncolsint, default: 1 Number of rows/columns of the subplot grid. sharex, shareybool or {'none', 'all', 'row', 'col'}, default: False Controls sharing of x-axis (sharex) or y-axis (sharey): True or 'all': x- or y-axis will be shared among all subplots. False or 'none': each subplot x- or y-axis will be independent. 'row': each subplot row will share an x- or y-axis. 'col': each subplot column will share an x- or y-axis. When subplots have a shared x-axis along a column, only the x tick labels of the bottom subplot are created. Similarly, when subplots have a shared y-axis along a row, only the y tick labels of the first column subplot are created. To later turn other subplots' ticklabels on, use tick_params. When subplots have a shared axis that has units, calling Axis.set_units will update each axis with the new units. squeezebool, default: True If True, extra dimensions are squeezed out from the returned array of Axes: if only one subplot is constructed (nrows=ncols=1), the resulting single Axes object is returned as a scalar. for Nx1 or 1xM subplots, the returned object is a 1D numpy object array of Axes objects. for NxM, subplots with N>1 and M>1 are returned as a 2D array. If False, no squeezing at all is done: the returned Axes object is always a 2D array containing Axes instances, even if it ends up being 1x1. subplot_kwdict, optional Dict with keywords passed to the Figure.add_subplot call used to create each subplot. gridspec_kwdict, optional Dict with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on. Returns Axes or array of Axes Either a single Axes object or an array of Axes objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above. See also pyplot.subplots Figure.add_subplot pyplot.subplot Examples # First create some toy data: x = np.linspace(0, 2*np.pi, 400) y = np.sin(x**2) # Create a figure plt.figure() # Create a subplot ax = fig.subplots() ax.plot(x, y) ax.set_title('Simple plot') # Create two subplots and unpack the output array immediately ax1, ax2 = fig.subplots(1, 2, sharey=True) ax1.plot(x, y) ax1.set_title('Sharing Y axis') ax2.scatter(x, y) # Create four polar Axes and access them through the returned array axes = fig.subplots(2, 2, subplot_kw=dict(projection='polar')) axes[0, 0].plot(x, y) axes[1, 1].scatter(x, y) # Share a X axis with each column of subplots fig.subplots(2, 2, sharex='col') # Share a Y axis with each row of subplots fig.subplots(2, 2, sharey='row') # Share both X and Y axes with all subplots fig.subplots(2, 2, sharex='all', sharey='all') # Note that this is the same as fig.subplots(2, 2, sharex=True, sharey=True) subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)[source] Adjust the subplot layout parameters. Unset parameters are left unmodified; initial values are given by rcParams["figure.subplot.[name]"]. Parameters leftfloat, optional The position of the left edge of the subplots, as a fraction of the figure width. rightfloat, optional The position of the right edge of the subplots, as a fraction of the figure width. bottomfloat, optional The position of the bottom edge of the subplots, as a fraction of the figure height. topfloat, optional The position of the top edge of the subplots, as a fraction of the figure height. wspacefloat, optional The width of the padding between subplots, as a fraction of the average Axes width. hspacefloat, optional The height of the padding between subplots, as a fraction of the average Axes height. suptitle(t, **kwargs)[source] Add a centered suptitle to the figure. Parameters tstr The suptitle text. xfloat, default: 0.5 The x location of the text in figure coordinates. yfloat, default: 0.98 The y location of the text in figure coordinates. horizontalalignment, ha{'center', 'left', 'right'}, default: center The horizontal alignment of the text relative to (x, y). verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: top The vertical alignment of the text relative to (x, y). fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large') The font size of the text. See Text.set_size for possible values. fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal') The font weight of the text. See Text.set_weight for possible values. Returns text The Text instance of the suptitle. Other Parameters fontpropertiesNone or dict, optional A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case. **kwargs Additional kwargs are matplotlib.text.Text properties. supxlabel(t, **kwargs)[source] Add a centered supxlabel to the figure. Parameters tstr The supxlabel text. xfloat, default: 0.5 The x location of the text in figure coordinates. yfloat, default: 0.01 The y location of the text in figure coordinates. horizontalalignment, ha{'center', 'left', 'right'}, default: center The horizontal alignment of the text relative to (x, y). verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: bottom The vertical alignment of the text relative to (x, y). fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large') The font size of the text. See Text.set_size for possible values. fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal') The font weight of the text. See Text.set_weight for possible values. Returns text The Text instance of the supxlabel. Other Parameters fontpropertiesNone or dict, optional A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case. **kwargs Additional kwargs are matplotlib.text.Text properties. supylabel(t, **kwargs)[source] Add a centered supylabel to the figure. Parameters tstr The supylabel text. xfloat, default: 0.02 The x location of the text in figure coordinates. yfloat, default: 0.5 The y location of the text in figure coordinates. horizontalalignment, ha{'center', 'left', 'right'}, default: left The horizontal alignment of the text relative to (x, y). verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: center The vertical alignment of the text relative to (x, y). fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large') The font size of the text. See Text.set_size for possible values. fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal') The font weight of the text. See Text.set_weight for possible values. Returns text The Text instance of the supylabel. Other Parameters fontpropertiesNone or dict, optional A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case. **kwargs Additional kwargs are matplotlib.text.Text properties. text(x, y, s, fontdict=None, **kwargs)[source] Add text to figure. Parameters x, yfloat The position to place the text. By default, this is in figure coordinates, floats in [0, 1]. The coordinate system can be changed using the transform keyword. sstr The text string. fontdictdict, optional A dictionary to override the default text properties. If not given, the defaults are determined by rcParams["font.*"]. Properties passed as kwargs override the corresponding ones given in fontdict. Returns Text Other Parameters **kwargsText properties Other miscellaneous text parameters. Property Description agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha scalar or None animated bool backgroundcolor color bbox dict with properties for patches.FancyBboxPatch clip_box unknown clip_on unknown clip_path unknown color or c color figure Figure fontfamily or family {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'} fontproperties or font or font_properties font_manager.FontProperties or str or pathlib.Path fontsize or size float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'} fontstretch or stretch {a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'} fontstyle or style {'normal', 'italic', 'oblique'} fontvariant or variant {'normal', 'small-caps'} fontweight or weight {a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'} gid str horizontalalignment or ha {'center', 'right', 'left'} in_layout bool label object linespacing float (multiple of font size) math_fontfamily str multialignment or ma {'left', 'right', 'center'} parse_math bool path_effects AbstractPathEffect picker None or bool or float or callable position (float, float) rasterized bool rotation float or {'vertical', 'horizontal'} rotation_mode {None, 'default', 'anchor'} sketch_params (scale: float, length: float, randomness: float) snap bool or None text object transform Transform transform_rotates_text bool url str usetex bool or None verticalalignment or va {'center', 'top', 'bottom', 'baseline', 'center_baseline'} visible bool wrap bool x float y float zorder float See also Axes.text pyplot.text update(props)[source] Update this artist's properties from the dict props. Parameters propsdict update_from(other)[source] Copy properties from other to self. zorder=0
doc_3
The object passed as the tzinfo argument to the datetime constructor, or None if none was passed.
doc_4
Reads and returns at most n frames of audio, as a bytes object.
doc_5
Check if windows match. New in version 1.6.0. Parameters otherclass instance The other class must have the window attribute. Returns boolboolean True if the windows are the same, False otherwise.
doc_6
The maximum number of frames to include in tracebacks output by the default log_exception() method. If None, all frames are included.
doc_7
class collections.abc.MutableMapping ABCs for read-only and mutable mappings.
doc_8
Set the result for this Future, which will mark this Future as completed and trigger all attached callbacks. Note that a Future cannot be marked completed twice. Parameters result (object) – the result object of this Future. Example:: >>> import threading >>> import time >>> import torch >>> >>> def slow_set_future(fut, value): >>> time.sleep(0.5) >>> fut.set_result(value) >>> >>> fut = torch.futures.Future() >>> t = threading.Thread( >>> target=slow_set_future, >>> args=(fut, torch.ones(2) * 3) >>> ) >>> t.start() >>> >>> print(fut.wait()) # tensor([3., 3.]) >>> t.join()
doc_9
Return the names of the available scales.
doc_10
Efficiently redraw Axes data, but not axis ticks, labels, etc. This method can only be used after an initial draw which caches the renderer.
doc_11
Concrete implementation of InspectLoader.is_package(). A module is determined to be a package if its file path (as provided by ExecutionLoader.get_filename()) is a file named __init__ when the file extension is removed and the module name itself does not end in __init__.
doc_12
Return cumulative distribution function (cdf) for the given image. Parameters imagearray Image array. nbinsint, optional Number of bins for image histogram. Returns img_cdfarray Values of cumulative distribution function. bin_centersarray Centers of bins. See also histogram References 1 https://en.wikipedia.org/wiki/Cumulative_distribution_function Examples >>> from skimage import data, exposure, img_as_float >>> image = img_as_float(data.camera()) >>> hi = exposure.histogram(image) >>> cdf = exposure.cumulative_distribution(image) >>> np.alltrue(cdf[0] == np.cumsum(hi[0])/float(image.size)) True
doc_13
Bases: skimage.viewer.plugins.base.Plugin __init__(max_radius=20, **kwargs) [source] Initialize self. See help(type(self)) for accurate signature. attach(image_viewer) [source] Attach the plugin to an ImageViewer. Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example: viewer += Plugin(...) Also note that attach automatically calls the filter function so that the image matches the filtered value specified by attached widgets. help() [source] property label name = 'LabelPainter' on_enter(overlay) [source] property radius
doc_14
__delitem__(key) discard(key) These methods immediately delete the message. The MH convention of marking a message for deletion by prepending a comma to its name is not used.
doc_15
Convert an IRI to a URI. All non-ASCII and unsafe characters are quoted. If the URL has a domain, it is encoded to Punycode. >>> iri_to_uri('http://\u2603.net/p\xe5th?q=\xe8ry%DF') 'http://xn--n3h.net/p%C3%A5th?q=%C3%A8ry%DF' Parameters iri (Union[str, Tuple[str, str, str, str, str]]) – The IRI to convert. charset (str) – The encoding of the IRI. errors (str) – Error handler to use during bytes.encode. safe_conversion (bool) – Return the URL unchanged if it only contains ASCII characters and no whitespace. See the explanation below. Return type str There is a general problem with IRI conversion with some protocols that are in violation of the URI specification. Consider the following two IRIs: magnet:?xt=uri:whatever itms-services://?action=download-manifest After parsing, we don’t know if the scheme requires the //, which is dropped if empty, but conveys different meanings in the final URL if it’s present or not. In this case, you can use safe_conversion, which will return the URL unchanged if it only contains ASCII characters and no whitespace. This can result in a URI with unquoted characters if it was not already quoted correctly, but preserves the URL’s semantics. Werkzeug uses this for the Location header for redirects. Changelog Changed in version 0.15: All reserved characters remain unquoted. Previously, only some reserved characters were left unquoted. Changed in version 0.9.6: The safe_conversion parameter was added. New in version 0.6.
doc_16
A function that checks if django.contrib.sites is installed and returns either the current Site object or a RequestSite object based on the request. It looks up the current site based on request.get_host() if the SITE_ID setting is not defined. Both a domain and a port may be returned by request.get_host() when the Host header has a port explicitly specified, e.g. example.com:80. In such cases, if the lookup fails because the host does not match a record in the database, the port is stripped and the lookup is retried with the domain part only. This does not apply to RequestSite which will always use the unmodified host.
doc_17
Find indices where elements of v should be inserted in a to maintain order. For full documentation, see numpy.searchsorted See also numpy.searchsorted equivalent function
doc_18
Legendre series whose graph is a straight line. Parameters off, sclscalars The specified line is given by off + scl*x. Returns yndarray This module’s representation of the Legendre series for off + scl*x. See also numpy.polynomial.polynomial.polyline numpy.polynomial.chebyshev.chebline numpy.polynomial.laguerre.lagline numpy.polynomial.hermite.hermline numpy.polynomial.hermite_e.hermeline Examples >>> import numpy.polynomial.legendre as L >>> L.legline(3,2) array([3, 2]) >>> L.legval(-3, L.legline(3,2)) # should be -3 -3.0
doc_19
Applies Instance Normalization over a 5D input (a mini-batch of 3D inputs with additional channel dimension) as described in the paper Instance Normalization: The Missing Ingredient for Fast Stylization. y=x−E[x]Var[x]+ϵ∗γ+βy = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta The mean and standard-deviation are calculated per-dimension separately for each object in a mini-batch. γ\gamma and β\beta are learnable parameter vectors of size C (where C is the input size) if affine is True. The standard-deviation is calculated via the biased estimator, equivalent to torch.var(input, unbiased=False). By default, this layer uses instance statistics computed from input data in both training and evaluation modes. If track_running_stats is set to True, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default momentum of 0.1. Note This momentum argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is x^new=(1−momentum)×x^+momentum×xt\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t , where x^\hat{x} is the estimated statistic and xtx_t is the new observed value. Note InstanceNorm3d and LayerNorm are very similar, but have some subtle differences. InstanceNorm3d is applied on each channel of channeled data like 3D models with RGB color, but LayerNorm is usually applied on entire sample and often in NLP tasks. Additionally, LayerNorm applies elementwise affine transform, while InstanceNorm3d usually don’t apply affine transform. Parameters num_features – CC from an expected input of size (N,C,D,H,W)(N, C, D, H, W) eps – a value added to the denominator for numerical stability. Default: 1e-5 momentum – the value used for the running_mean and running_var computation. Default: 0.1 affine – a boolean value that when set to True, this module has learnable affine parameters, initialized the same way as done for batch normalization. Default: False. track_running_stats – a boolean value that when set to True, this module tracks the running mean and variance, and when set to False, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: False Shape: Input: (N,C,D,H,W)(N, C, D, H, W) Output: (N,C,D,H,W)(N, C, D, H, W) (same shape as input) Examples: >>> # Without Learnable Parameters >>> m = nn.InstanceNorm3d(100) >>> # With Learnable Parameters >>> m = nn.InstanceNorm3d(100, affine=True) >>> input = torch.randn(20, 100, 35, 45, 10) >>> output = m(input)
doc_20
Alias for get_linewidth.
doc_21
Conversion from the sRGB color space (IEC 61966-2-1:1999) to the CIE Lab colorspace under the given illuminant and observer. Parameters rgb(…, 3) array_like The image in RGB format. Final dimension denotes channels. illuminant{“A”, “D50”, “D55”, “D65”, “D75”, “E”}, optional The name of the illuminant (the function is NOT case sensitive). observer{“2”, “10”}, optional The aperture angle of the observer. Returns out(…, 3) ndarray The image in Lab format. Same dimensions as input. Raises ValueError If rgb is not at least 2-D with shape (…, 3). Notes RGB is a device-dependent color space so, if you use this function, be sure that the image you are analyzing has been mapped to the sRGB color space. This function uses rgb2xyz and xyz2lab. By default Observer= 2A, Illuminant= D65. CIE XYZ tristimulus values x_ref=95.047, y_ref=100., z_ref=108.883. See function get_xyz_coords for a list of supported illuminants. References 1 https://en.wikipedia.org/wiki/Standard_illuminant
doc_22
See Migration guide for more details. tf.compat.v1.raw_ops.BatchFFT tf.raw_ops.BatchFFT( input, name=None ) Args input A Tensor of type complex64. name A name for the operation (optional). Returns A Tensor of type complex64.
doc_23
Raised by any of the functions when an error is detected.
doc_24
Find indices where elements should be inserted to maintain order. Find the indices into a sorted array self (a) such that, if the corresponding elements in value were inserted before the indices, the order of self would be preserved. Assuming that self is sorted: side returned index i satisfies left self[i-1] < value <= self[i] right self[i-1] <= value < self[i] Parameters value:array-like, list or scalar Value(s) to insert into self. side:{‘left’, ‘right’}, optional If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of self). sorter:1-D array-like, optional Optional array of integer indices that sort array a into ascending order. They are typically the result of argsort. Returns array of ints or int If value is array-like, array of insertion points. If value is scalar, a single integer. See also numpy.searchsorted Similar method from NumPy.
doc_25
A subclass of ConnectionError, raised when a connection attempt is refused by the peer. Corresponds to errno ECONNREFUSED.
doc_26
Path to the extension module.
doc_27
Filter an image with the Sato tubeness filter. This filter can be used to detect continuous ridges, e.g. tubes, wrinkles, rivers. It can be used to calculate the fraction of the whole image containing such objects. Defined only for 2-D and 3-D images. Calculates the eigenvectors of the Hessian to compute the similarity of an image region to tubes, according to the method described in [1]. Parameters image(N, M[, P]) ndarray Array with input image data. sigmasiterable of floats, optional Sigmas used as scales of filter. black_ridgesboolean, optional When True (the default), the filter detects black ridges; when False, it detects white ridges. mode{‘constant’, ‘reflect’, ‘wrap’, ‘nearest’, ‘mirror’}, optional How to handle values outside the image borders. cvalfloat, optional Used in conjunction with mode ‘constant’, the value outside the image boundaries. Returns out(N, M[, P]) ndarray Filtered image (maximum of pixels across all scales). See also meijering frangi hessian References 1 Sato, Y., Nakajima, S., Shiraga, N., Atsumi, H., Yoshida, S., Koller, T., …, Kikinis, R. (1998). Three-dimensional multi-scale line filter for segmentation and visualization of curvilinear structures in medical images. Medical image analysis, 2(2), 143-168. DOI:10.1016/S1361-8415(98)80009-1
doc_28
Return a tuple containing names of nonlocals in this function.
doc_29
sys.stdout sys.stderr File objects used by the interpreter for standard input, output and errors: stdin is used for all interactive input (including calls to input()); stdout is used for the output of print() and expression statements and for the prompts of input(); The interpreter’s own prompts and its error messages go to stderr. These streams are regular text files like those returned by the open() function. Their parameters are chosen as follows: The character encoding is platform-dependent. Non-Windows platforms use the locale encoding (see locale.getpreferredencoding()). On Windows, UTF-8 is used for the console device. Non-character devices such as disk files and pipes use the system locale encoding (i.e. the ANSI codepage). Non-console character devices such as NUL (i.e. where isatty() returns True) use the value of the console input and output codepages at startup, respectively for stdin and stdout/stderr. This defaults to the system locale encoding if the process is not initially attached to a console. The special behaviour of the console can be overridden by setting the environment variable PYTHONLEGACYWINDOWSSTDIO before starting Python. In that case, the console codepages are used as for any other character device. Under all platforms, you can override the character encoding by setting the PYTHONIOENCODING environment variable before starting Python or by using the new -X utf8 command line option and PYTHONUTF8 environment variable. However, for the Windows console, this only applies when PYTHONLEGACYWINDOWSSTDIO is also set. When interactive, the stdout stream is line-buffered. Otherwise, it is block-buffered like regular text files. The stderr stream is line-buffered in both cases. You can make both streams unbuffered by passing the -u command-line option or setting the PYTHONUNBUFFERED environment variable. Changed in version 3.9: Non-interactive stderr is now line-buffered instead of fully buffered. Note To write or read binary data from/to the standard streams, use the underlying binary buffer object. For example, to write bytes to stdout, use sys.stdout.buffer.write(b'abc'). However, if you are writing a library (and do not control in which context its code will be executed), be aware that the standard streams may be replaced with file-like objects like io.StringIO which do not support the buffer attribute.
doc_30
Return series instance that has the specified roots. Returns a series representing the product (x - r[0])*(x - r[1])*...*(x - r[n-1]), where r is a list of roots. Parameters rootsarray_like List of roots. domain{[], None, array_like}, optional Domain for the resulting series. If None the domain is the interval from the smallest root to the largest. If [] the domain is the class domain. The default is []. window{None, array_like}, optional Window for the returned series. If None the class window is used. The default is None. Returns new_seriesseries Series with the specified roots.
doc_31
input_type: 'number' template_name: 'django/forms/widgets/number.html' Renders as: <input type="number" ...> Beware that not all browsers support entering localized numbers in number input types. Django itself avoids using them for fields having their localize property set to True.
doc_32
The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.
doc_33
Fills self tensor with elements drawn from the exponential distribution: f(x)=λe−λxf(x) = \lambda e^{-\lambda x}
doc_34
Schedule all currently open asynchronous generator objects to close with an aclose() call. After calling this method, the event loop will issue a warning if a new asynchronous generator is iterated. This should be used to reliably finalize all scheduled asynchronous generators. Note that there is no need to call this function when asyncio.run() is used. Example: try: loop.run_forever() finally: loop.run_until_complete(loop.shutdown_asyncgens()) loop.close() New in version 3.6.
doc_35
Return True if the event is set.
doc_36
os.R_OK os.W_OK os.X_OK Values to pass as the mode parameter of access() to test the existence, readability, writability and executability of path, respectively.
doc_37
Call self as a function.
doc_38
Returns the name of the field that contains the date data that this view will operate on. Returns date_field by default.
doc_39
Restore the graphics context from the stack - needed only for backends that save graphics contexts on a stack.
doc_40
Bases: object The LatexManager opens an instance of the LaTeX application for determining the metrics of text elements. The LaTeX environment can be modified by setting fonts and/or a custom preamble in rcParams. get_width_height_descent(text, prop)[source] Get the width, total height, and descent (in TeX points) for a text typeset by the current LaTeX environment. propertystr_cache[source]
doc_41
tf.compat.v1.estimator.tpu.TPUEstimator( model_fn=None, model_dir=None, config=None, params=None, use_tpu=True, train_batch_size=None, eval_batch_size=None, predict_batch_size=None, batch_axis=None, eval_on_tpu=True, export_to_tpu=True, export_to_cpu=True, warm_start_from=None, embedding_config_spec=None, export_saved_model_api_version=ExportSavedModelApiVersion.V1 ) TPUEstimator also supports training on CPU and GPU. You don't need to define a separate tf.estimator.Estimator. TPUEstimator handles many of the details of running on TPU devices, such as replicating inputs and models for each core, and returning to host periodically to run hooks. TPUEstimator transforms a global batch size in params to a per-shard batch size when calling the input_fn and model_fn. Users should specify global batch size in constructor, and then get the batch size for each shard in input_fn and model_fn by params['batch_size']. For training, model_fn gets per-core batch size; input_fn may get per-core or per-host batch size depending on per_host_input_for_training in TPUConfig (See docstring for TPUConfig for details). For evaluation and prediction, model_fn gets per-core batch size and input_fn get per-host batch size. Evaluation model_fn should return TPUEstimatorSpec, which expects the eval_metrics for TPU evaluation. If eval_on_tpu is False, the evaluation will execute on CPU or GPU; in this case the following discussion on TPU evaluation does not apply. TPUEstimatorSpec.eval_metrics is a tuple of metric_fn and tensors, where tensors could be a list of any nested structure of Tensors (See TPUEstimatorSpec for details). metric_fn takes the tensors and returns a dict from metric string name to the result of calling a metric function, namely a (metric_tensor, update_op) tuple. One can set use_tpu to False for testing. All training, evaluation, and predict will be executed on CPU. input_fn and model_fn will receive train_batch_size or eval_batch_size unmodified as params['batch_size']. Current limitations: TPU evaluation only works on a single host (one TPU worker) except BROADCAST mode. input_fn for evaluation should NOT raise an end-of-input exception (OutOfRangeError or StopIteration). And all evaluation steps and all batches should have the same size. Example (MNIST): # The metric Fn which runs on CPU. def metric_fn(labels, logits): predictions = tf.argmax(logits, 1) return { 'accuracy': tf.compat.v1.metrics.precision( labels=labels, predictions=predictions), } # Your model Fn which runs on TPU (eval_metrics is list in this example) def model_fn(features, labels, mode, config, params): ... logits = ... if mode = tf.estimator.ModeKeys.EVAL: return tpu_estimator.TPUEstimatorSpec( mode=mode, loss=loss, eval_metrics=(metric_fn, [labels, logits])) # or specify the eval_metrics tensors as dict. def model_fn(features, labels, mode, config, params): ... final_layer_output = ... if mode = tf.estimator.ModeKeys.EVAL: return tpu_estimator.TPUEstimatorSpec( mode=mode, loss=loss, eval_metrics=(metric_fn, { 'labels': labels, 'logits': final_layer_output, })) Prediction Prediction on TPU is an experimental feature to support large batch inference. It is not designed for latency-critical system. In addition, due to some usability issues, for prediction with small dataset, CPU .predict, i.e., creating a new TPUEstimator instance with use_tpu=False, might be more convenient. Note: In contrast to TPU training/evaluation, the input_fn for prediction should raise an end-of-input exception (OutOfRangeError or StopIteration), which serves as the stopping signal to TPUEstimator. To be precise, the ops created by input_fn produce one batch of the data. The predict() API processes one batch at a time. When reaching the end of the data source, an end-of-input exception should be raised by one of these operations. The user usually does not need to do this manually. As long as the dataset is not repeated forever, the tf.data API will raise an end-of-input exception automatically after the last batch has been produced. Note: Estimator.predict returns a Python generator. Please consume all the data from the generator so that TPUEstimator can shutdown the TPU system properly for user. Current limitations: TPU prediction only works on a single host (one TPU worker). input_fn must return a Dataset instance rather than features. In fact, .train() and .evaluate() also support Dataset as return value. Example (MNIST): height = 32 width = 32 total_examples = 100 def predict_input_fn(params): batch_size = params['batch_size'] images = tf.random.uniform( [total_examples, height, width, 3], minval=-1, maxval=1) dataset = tf.data.Dataset.from_tensor_slices(images) dataset = dataset.map(lambda images: {'image': images}) dataset = dataset.batch(batch_size) return dataset def model_fn(features, labels, params, mode): # Generate predictions, called 'output', from features['image'] if mode == tf.estimator.ModeKeys.PREDICT: return tf.contrib.tpu.TPUEstimatorSpec( mode=mode, predictions={ 'predictions': output, 'is_padding': features['is_padding'] }) tpu_est = TPUEstimator( model_fn=model_fn, ..., predict_batch_size=16) # Fully consume the generator so that TPUEstimator can shutdown the TPU # system. for item in tpu_est.predict(input_fn=input_fn): # Filter out item if the `is_padding` is 1. # Process the 'predictions' Exporting export_saved_model exports 2 metagraphs, one with saved_model.SERVING, and another with saved_model.SERVING and saved_model.TPU tags. At serving time, these tags are used to select the appropriate metagraph to load. Before running the graph on TPU, the TPU system needs to be initialized. If TensorFlow Serving model-server is used, this is done automatically. If not, please use session.run(tpu.initialize_system()). There are two versions of the API: 1 or 2. In V1, the exported CPU graph is model_fn as it is. The exported TPU graph wraps tpu.rewrite() and TPUPartitionedCallOp around model_fn so model_fn is on TPU by default. To place ops on CPU, tpu.outside_compilation(host_call, logits) can be used. Example: def model_fn(features, labels, mode, config, params): ... logits = ... export_outputs = { 'logits': export_output_lib.PredictOutput( {'logits': logits}) } def host_call(logits): class_ids = math_ops.argmax(logits) classes = string_ops.as_string(class_ids) export_outputs['classes'] = export_output_lib.ClassificationOutput(classes=classes) tpu.outside_compilation(host_call, logits) ... In V2, export_saved_model() sets up params['use_tpu'] flag to let the user know if the code is exporting to TPU (or not). When params['use_tpu'] is True, users need to call tpu.rewrite(), TPUPartitionedCallOp and/or batch_function(). Alternatively use inference_on_tpu() which is a convenience wrapper of the three. def model_fn(features, labels, mode, config, params): ... # This could be some pre-processing on CPU like calls to input layer with # embedding columns. x2 = features['x'] * 2 def computation(input_tensor): return layers.dense( input_tensor, 1, kernel_initializer=init_ops.zeros_initializer()) inputs = [x2] if params['use_tpu']: predictions = array_ops.identity( tpu_estimator.inference_on_tpu(computation, inputs, num_batch_threads=1, max_batch_size=2, batch_timeout_micros=100), name='predictions') else: predictions = array_ops.identity( computation(*inputs), name='predictions') key = signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY export_outputs = { key: export_lib.PredictOutput({'prediction': predictions}) } ... TIP: V2 is recommended as it is more flexible (eg: batching, etc). Args model_fn Model function as required by Estimator which returns EstimatorSpec or TPUEstimatorSpec. training_hooks, 'evaluation_hooks', and prediction_hooks must not capure any TPU Tensor inside the model_fn. model_dir Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. If None, the model_dir in config will be used if set. If both are set, they must be same. If both are None, a temporary directory will be used. config An tpu_config.RunConfig configuration object. Cannot be None. params An optional dict of hyper parameters that will be passed into input_fn and model_fn. Keys are names of parameters, values are basic python types. There are reserved keys for TPUEstimator, including 'batch_size'. use_tpu A bool indicating whether TPU support is enabled. Currently, - TPU training and evaluation respect this bit, but eval_on_tpu can override execution of eval. See below. train_batch_size An int representing the global training batch size. TPUEstimator transforms this global batch size to a per-shard batch size, as params['batch_size'], when calling input_fn and model_fn. Cannot be None if use_tpu is True. Must be divisible by total number of replicas. eval_batch_size An int representing evaluation batch size. Must be divisible by total number of replicas. predict_batch_size An int representing the prediction batch size. Must be divisible by total number of replicas. batch_axis A python tuple of int values describing how each tensor produced by the Estimator input_fn should be split across the TPU compute shards. For example, if your input_fn produced (images, labels) where the images tensor is in HWCN format, your shard dimensions would be [3, 0], where 3 corresponds to the N dimension of your images Tensor, and 0 corresponds to the dimension along which to split the labels to match up with the corresponding images. If None is supplied, and per_host_input_for_training is True, batches will be sharded based on the major dimension. If tpu_config.per_host_input_for_training is False or PER_HOST_V2, batch_axis is ignored. eval_on_tpu If False, evaluation runs on CPU or GPU. In this case, the model_fn must return EstimatorSpec when called with mode as EVAL. export_to_tpu If True, export_saved_model() exports a metagraph for serving on TPU. Note that unsupported export modes such as EVAL will be ignored. For those modes, only a CPU model will be exported. Currently, export_to_tpu only supports PREDICT. export_to_cpu If True, export_saved_model() exports a metagraph for serving on CPU. warm_start_from Optional string filepath to a checkpoint or SavedModel to warm-start from, or a tf.estimator.WarmStartSettings object to fully configure warm-starting. If the string filepath is provided instead of a WarmStartSettings, then all variables are warm-started, and it is assumed that vocabularies and Tensor names are unchanged. embedding_config_spec Optional EmbeddingConfigSpec instance to support using TPU embedding. export_saved_model_api_version an integer: 1 or 2. 1 corresponds to V1, 2 corresponds to V2. (Defaults to V1). With V1, export_saved_model() adds rewrite() and TPUPartitionedCallOp() for user; while in v2, user is expected to add rewrite(), TPUPartitionedCallOp() etc in their model_fn. A helper function inference_on_tpu is provided for V2. brn_tpu_estimator.py includes examples for both versions i.e. TPUEstimatorExportTest and TPUEstimatorExportV2Test. Raises ValueError params has reserved keys already. Attributes config model_dir model_fn Returns the model_fn which is bound to self.params. params Methods eval_dir View source eval_dir( name=None ) Shows the directory name where evaluation metrics are dumped. Args name Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. Returns A string which is the path of directory contains evaluation metrics. evaluate View source evaluate( input_fn, steps=None, hooks=None, checkpoint_path=None, name=None ) Evaluates the model given evaluation data input_fn. For each step, calls input_fn, which returns one batch of data. Evaluates until: steps batches are processed, or input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration). Args input_fn A function that constructs the input data for evaluation. See Premade Estimators for more information. The function should construct and return one of the following: A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs. steps Number of steps for which to evaluate model. If None, evaluates until input_fn raises an end-of-input exception. hooks List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the evaluation call. checkpoint_path Path of a specific checkpoint to evaluate. If None, the latest checkpoint in model_dir is used. If there are no checkpoints in model_dir, evaluation is run with newly initialized Variables instead of ones restored from checkpoint. name Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. Returns A dict containing the evaluation metrics specified in model_fn keyed by name, as well as an entry global_step which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the loss (mean loss per mini-batch) and the average_loss (mean loss per sample). Canned classifiers also return the accuracy. Canned regressors also return the label/mean and the prediction/mean. Raises ValueError If steps <= 0. experimental_export_all_saved_models View source experimental_export_all_saved_models( export_dir_base, input_receiver_fn_map, assets_extra=None, as_text=False, checkpoint_path=None ) Exports a SavedModel with tf.MetaGraphDefs for each requested mode. For each mode passed in via the input_receiver_fn_map, this method builds a new graph by calling the input_receiver_fn to obtain feature and label Tensors. Next, this method calls the Estimator's model_fn in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the SavedModel (order of preference: tf.estimator.ModeKeys.TRAIN, tf.estimator.ModeKeys.EVAL, then tf.estimator.ModeKeys.PREDICT), such that up to three tf.MetaGraphDefs are saved with a single set of variables in a single SavedModel directory. For the variables and tf.MetaGraphDefs, a timestamped export directory below export_dir_base, and writes a SavedModel into it containing the tf.MetaGraphDef for the given mode and its associated signatures. For prediction, the exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn. For training and evaluation, the train_op is stored in an extra collection, and loss, metrics, and predictions are included in a SignatureDef for the mode in question. Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}. Args export_dir_base A string containing a directory in which to create timestamped subdirectories containing exported SavedModels. input_receiver_fn_map dict of tf.estimator.ModeKeys to input_receiver_fn mappings, where the input_receiver_fn is a function that takes no arguments and returns the appropriate subclass of InputReceiver. assets_extra A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed. as_text whether to write the SavedModel proto in text format. checkpoint_path The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen. Returns The path to the exported directory as a bytes object. Raises ValueError if any input_receiver_fn is None, no export_outputs are provided, or no checkpoint can be found. export_saved_model View source export_saved_model( export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False, checkpoint_path=None, experimental_mode=ModeKeys.PREDICT ) Exports inference graph as a SavedModel into the given dir. For a detailed guide, see SavedModel from Estimators. This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session. The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn. Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}. The experimental_mode parameter can be used to export a single train/eval/predict graph as a SavedModel. See experimental_export_all_saved_models for full docs. Args export_dir_base A string containing a directory in which to create timestamped subdirectories containing exported SavedModels. serving_input_receiver_fn A function that takes no argument and returns a tf.estimator.export.ServingInputReceiver or tf.estimator.export.TensorServingInputReceiver. assets_extra A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed. as_text whether to write the SavedModel proto in text format. checkpoint_path The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen. experimental_mode tf.estimator.ModeKeys value indicating with mode will be exported. Note that this feature is experimental. Returns The path to the exported directory as a bytes object. Raises ValueError if no serving_input_receiver_fn is provided, no export_outputs are provided, or no checkpoint can be found. export_savedmodel View source export_savedmodel( export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False, checkpoint_path=None, strip_default_attrs=False ) Exports inference graph as a SavedModel into the given dir. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: This function has been renamed, use export_saved_model instead. For a detailed guide, see SavedModel from Estimators. This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session. The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn. Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}. Args export_dir_base A string containing a directory in which to create timestamped subdirectories containing exported SavedModels. serving_input_receiver_fn A function that takes no argument and returns a tf.estimator.export.ServingInputReceiver or tf.estimator.export.TensorServingInputReceiver. assets_extra A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed. as_text whether to write the SavedModel proto in text format. checkpoint_path The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen. strip_default_attrs Boolean. If True, default-valued attributes will be removed from the NodeDefs. For a detailed guide, see Stripping Default-Valued Attributes. Returns The path to the exported directory as a bytes object. Raises ValueError if no serving_input_receiver_fn is provided, no export_outputs are provided, or no checkpoint can be found. get_variable_names View source get_variable_names() Returns list of all variable names in this model. Returns List of names. Raises ValueError If the Estimator has not produced a checkpoint yet. get_variable_value View source get_variable_value( name ) Returns value of the variable given by name. Args name string or a list of string, name of the tensor. Returns Numpy array - value of the tensor. Raises ValueError If the Estimator has not produced a checkpoint yet. latest_checkpoint View source latest_checkpoint() Finds the filename of the latest saved checkpoint file in model_dir. Returns The full path to the latest checkpoint or None if no checkpoint was found. predict View source predict( input_fn, predict_keys=None, hooks=None, checkpoint_path=None, yield_single_examples=True ) Yields predictions for given features. Please note that interleaving two predict outputs does not work. See: issue/20506 Args input_fn A function that constructs the features. Prediction continues until input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration). See Premade Estimators for more information. The function should construct and return one of the following: tf.data.Dataset object -- Outputs of Dataset object must have same constraints as below. features -- A tf.Tensor or a dictionary of string feature name to Tensor. features are consumed by model_fn. They should satisfy the expectation of model_fn from inputs. A tuple, in which case the first item is extracted as features. predict_keys list of str, name of the keys to predict. It is used if the tf.estimator.EstimatorSpec.predictions is a dict. If predict_keys is used then rest of the predictions will be filtered from the dictionary. If None, returns all. hooks List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the prediction call. checkpoint_path Path of a specific checkpoint to predict. If None, the latest checkpoint in model_dir is used. If there are no checkpoints in model_dir, prediction is run with newly initialized Variables instead of ones restored from checkpoint. yield_single_examples If False, yields the whole batch as returned by the model_fn instead of decomposing the batch into individual elements. This is useful if model_fn returns some tensors whose first dimension is not equal to the batch size. Yields Evaluated values of predictions tensors. Raises ValueError If batch length of predictions is not the same and yield_single_examples is True. ValueError If there is a conflict between predict_keys and predictions. For example if predict_keys is not None but tf.estimator.EstimatorSpec.predictions is not a dict. train View source train( input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None ) Trains a model given training data input_fn. Args input_fn A function that provides input data for training as minibatches. See Premade Estimators for more information. The function should construct and return one of the following: A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs. hooks List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the training loop. steps Number of steps for which to train the model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. steps works incrementally. If you call two times train(steps=10) then training occurs in total 20 steps. If OutOfRange or StopIteration occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set max_steps instead. If set, max_steps must be None. max_steps Number of total steps for which to train model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. If set, steps must be None. If OutOfRange or StopIteration occurs in the middle, training stops before max_steps steps. Two calls to train(steps=100) means 200 training iterations. On the other hand, two calls to train(max_steps=100) means that the second call will not do any iteration since first call did all 100 steps. saving_listeners list of CheckpointSaverListener objects. Used for callbacks that run immediately before or after checkpoint savings. Returns self, for chaining. Raises ValueError If both steps and max_steps are not None. ValueError If either steps or max_steps <= 0.
doc_42
Prompt the user for a password without echoing. The user is prompted using the string prompt, which defaults to 'Password: '. On Unix, the prompt is written to the file-like object stream using the replace error handler if needed. stream defaults to the controlling terminal (/dev/tty) or if that is unavailable to sys.stderr (this argument is ignored on Windows). If echo free input is unavailable getpass() falls back to printing a warning message to stream and reading from sys.stdin and issuing a GetPassWarning. Note If you call getpass from within IDLE, the input may be done in the terminal you launched IDLE from rather than the idle window itself.
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
3