magicclass.widgets package

Subpackages

Submodules

magicclass.widgets.color module

class magicclass.widgets.color.QColorEdit(parent=None, value: str = 'white')[source]

Bases: PyQt5.QtWidgets.QWidget

color()[source]

Return the current color.

colorChanged
setColor(color)[source]

Set value as the current color.

class magicclass.widgets.color.QColorLineEdit(parent=None)[source]

Bases: PyQt5.QtWidgets.QLineEdit

getQColor() PyQt5.QtGui.QColor[source]

Get color as QColor object

setColor(color: QColor | str)[source]
setText(color: str | Iterable[float])[source]

Set the text of the lineEdit using any ColorType.

Colors will be converted to standard SVG spec names if possible, or shown as #RGBA hex if not.

Parameters

color (ColorType) -- Can be any ColorType recognized by our utils.colormaps.standardize_color.transform_color function.

class magicclass.widgets.color.QColorSlider(parent=None, value='white')[source]

Bases: PyQt5.QtWidgets.QWidget

addSlider(label: str)[source]
color()[source]

Return the current color.

colorChanged
setColor(color)[source]

Set value as the current color.

class magicclass.widgets.color.QColorSwatch(parent=None)[source]

Bases: PyQt5.QtWidgets.QFrame

colorChanged
getQColor() PyQt5.QtGui.QColor[source]
heightForWidth(self, int) int[source]
mouseReleaseEvent(event)[source]

Show QColorPopup picker when the user clicks on the swatch.

setColor(color: PyQt5.QtGui.QColor) None[source]
class magicclass.widgets.color.QDoubleSlider(parent=None, decimals: int = 3)[source]

Bases: PyQt5.QtWidgets.QSlider

changed
doubleValueChanged()[source]
setMaximum(self, int)[source]
setMinimum(self, int)[source]
setSingleStep(self, int)[source]
setValue(self, int)[source]
singleStep(self) int[source]
value(self) int[source]
magicclass.widgets.color.qcolor_to_rgba(qcolor: PyQt5.QtGui.QColor) tuple[float, float, float, float][source]
magicclass.widgets.color.rgba_to_html(rgba: Iterable[float]) str[source]
magicclass.widgets.color.rgba_to_qcolor(rgba: Iterable[float]) PyQt5.QtGui.QColor[source]

magicclass.widgets.containers module

magicclass.widgets.containers.wrap_container(cls: type[C] = None, base: type = None) Callable | type[C][source]

Provide a wrapper for a new container widget with a new protocol.

magicclass.widgets.logger module

class magicclass.widgets.logger.Logger[source]

Bases: magicgui.widgets._bases.widget.Widget, logging.Handler

A widget for logging.

Examples

Create widget as other magicgui or magicclass widgets.

logger = Logger(name="my logger")  # magicgui way

# magicclass way
@magicclass
class Main:
    logger = field(Logger, name="my logger")

# This is OK
@magicclass
class Main:
    logger = Logger()

Print something in the widget

# print something in the widget.
logger.print("text")

# a context manager that change the destination of print function.
with logger.set_stdout():
    print("text")
    function_that_print_something()

# permanently change the destination of print function
sys.stdout = logger

Logging in the widget

with logger.set_logger():
    function_that_log_something()

logging.getLogger(__name__).addHandler(logger)

Inline plot in the widget

with logger.set_plt():
    plt.plot(np.random.random(100))
clear()[source]

Clear all the histories.

close() None[source]

Close widget.

current_logger: Logger | None = None
emit(record)[source]

Do whatever it takes to actually log the specified logging record.

This version is intended to be implemented by subclasses and so raises a NotImplementedError.

flush()[source]

Ensure all logging output has been flushed.

This version does nothing and is intended to be implemented by subclasses.

print(*msg, sep=' ', end='\n')[source]

Print things in the end of the logger widget.

print_figure(fig: Figure) None[source]

Print matplotlib Figure object like inline plot.

print_html(html: str, end='<br></br>')[source]

Print things in the end of the logger widget using HTML string.

print_image(arr: str | Path | np.ndarray | Image, vmin=None, vmax=None, cmap=None, norm=None, width=None, height=None) None[source]

Print an array as an image in the logger widget. Can be a path.

print_rst(rst: str, end='\n')[source]

Print things in the end of the logger widget using rST string.

print_table(table, header: bool = True, index: bool = True, precision: int | None = None)[source]

Print object as a table in the logger widget.

Parameters
  • table (table-like object) -- Any object that can be passed to pandas.DataFrame can be used.

  • header (bool, default is True) -- Whether to show the header row.

  • index (bool, default is True) -- Whether to show the index column.

  • precision (int, options) -- If given, float value will be rounded by this parameter.

set_logger(name=None)[source]

A context manager for logging things in this widget.

set_plt(style: str | None) None[source]
set_plt(rc_context: dict[str, Any]) None

A context manager for inline plot in the logger widget.

set_stdout()[source]

A context manager for printing things in this widget.

write(msg) None[source]
class magicclass.widgets.logger.Output[source]

Bases: object

HTML = 1
IMAGE = 2
TEXT = 0
class magicclass.widgets.logger.QtLogger(parent=None, max_history: int = 500)[source]

Bases: PyQt5.QtWidgets.QTextEdit

appendHtml(html: str)[source]

Append HTML in the main thread.

appendImage(qimage: PyQt5.QtGui.QImage)[source]

Append image in the main thread.

appendText(text: str)[source]

Append text in the main thread.

process
update(self)[source]
update(self, QRect) None
update(self, QRegion) None
QtLogger.update(self, int, int, int, int) -> None
magicclass.widgets.logger.show(close=True, block=None)[source]

magicclass.widgets.misc module

class magicclass.widgets.misc.AbstractRangeSlider(value=UNSET, min=0, max=1000, orientation: str = 'horizontal', nullable: bool = True, **kwargs)[source]

Bases: magicgui.widgets._bases.value_widget.ValueWidget, Generic[magicclass.widgets.misc._V]

A slider widget that represent a range like (2, 5).

This class is a temporary one and may be substituted by magicgui widget soon. See https://github.com/napari/magicgui/pull/337.

changed

Signal descriptor, for declaring a signal on a class.

This is designed to be used as a class attribute, with the supported signature(s) provided in the contructor:

class MyEmitter:

changed = Signal(int) # changed will emit an int

def receiver(arg: int):

print("new value:", arg)

emitter = MyEmitter() emitter.changed.connect(receiver) emitter.emit(1)

Note: in the example above, MyEmitter.changed is an instance of Signal, and emitter.changed is an instance of SignalInstance.

Parameters
  • *types (sequence of Type) -- A sequence of individual types

  • description (str, optional) -- Optional descriptive text for the signal. (not used internally).

  • name (str, optional) -- Optional name of the signal. If it is not specified then the name of the class attribute that is bound to the signal will be used. default None

  • check_nargs_on_connect (str, optional) -- Whether to check the number of positional args against signature when connecting a new callback. This can also be provided at connection time using .connect(..., check_nargs=True). By default, True.

  • check_types_on_connect (str, optional) -- Whether to check the callback parameter types against signature when connecting a new callback. This can also be provided at connection time using .connect(..., check_types=True). By default, False.

property max: magicclass.widgets.misc._V
property min: magicclass.widgets.misc._V
property range: tuple[~_V, ~_V]
property value: tuple[~_V, ~_V]

Return current value of the widget. This may be interpreted by backends.

class magicclass.widgets.misc.CheckButton(text: str | None = None, **kwargs)[source]

Bases: magicgui.widgets.PushButton

A checkable button.

class magicclass.widgets.misc.ConsoleTextEdit(*args, **kwargs)[source]

Bases: magicgui.widgets.TextEdit

A text edit with console-like setting.

append(text: str)[source]

Append new text.

erase_first()[source]

Erase the first line.

erase_last()[source]

Erase the last line.

property selected: str

Return selected string.

property tab_size
class magicclass.widgets.misc.Figure(nrows: int = 1, ncols: int = 1, figsize: tuple[float, float] = (4.0, 3.0), style=None, **kwargs)[source]

Bases: magicclass.widgets.utils.FreeWidget

A matplotlib figure canvas.

autoscale(enable=True, axis='both', tight=None)[source]

Copy of plt.autoscale(). Original docstring is ...

Autoscale the axis view to the data (toggle).

Convenience method for simple axis view autoscaling. It turns autoscaling on or off, and then, if autoscaling for either axis is on, it performs the autoscaling on the specified axis or axes.

Parameters
  • enable (bool or None, default: True) -- True turns autoscaling on, False turns it off. None leaves the autoscaling state unchanged.

  • axis ({'both', 'x', 'y'}, default: 'both') -- Which axis to operate on.

  • tight (bool or None, default: None) -- If True, first set the margins to zero. Then, this argument is forwarded to autoscale_view (regardless of its value); see the description of its behavior there.

property ax: Axes

The first matplotlib axis.

property axes: list[Axes]

List of matplotlib axes.

axhline(y=0, xmin=0, xmax=1, **kwargs)[source]

Copy of plt.axhline(). Original docstring is ...

Add a horizontal line across the axis.

Parameters
  • y (float, default: 0) -- y position in data coordinates of the horizontal line.

  • xmin (float, default: 0) -- Should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot.

  • xmax (float, default: 1) -- Should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot.

  • **kwargs --

    Valid keyword arguments are .Line2D properties, with the exception of 'transform':

    Properties: 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 antialiased or aa: bool clip_box: .Bbox clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color contains: unknown dash_capstyle: .CapStyle or {'butt', 'projecting', 'round'} dash_joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default' figure: .Figure fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'} gid: str in_layout: bool label: object linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: color markeredgewidth or mew: float markerfacecolor or mfc: color markerfacecoloralt or mfcalt: color markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] path_effects: .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {'butt', 'projecting', 'round'} solid_joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} transform: matplotlib.transforms.Transform url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns

Return type

~matplotlib.lines.Line2D

See also

hlines

Add horizontal lines in data coordinates.

axhspan

Add a horizontal span (rectangle) across the axis.

axline

Add a line with an arbitrary slope.

Examples

  • draw a thick red hline at 'y' = 0 that spans the xrange:

    >>> axhline(linewidth=4, color='r')
    
  • draw a default hline at 'y' = 1 that spans the xrange:

    >>> axhline(y=1)
    
  • draw a default hline at 'y' = .5 that spans the middle half of the xrange:

    >>> axhline(y=.5, xmin=0.25, xmax=0.75)
    
axline(xy1, xy2=None, *, slope=None, **kwargs)[source]

Copy of plt.axline(). Original docstring is ...

Add an infinitely long straight line.

The line can be defined either by two points xy1 and xy2, or by one point xy1 and a slope.

This draws a straight line "on the screen", regardless of the x and y scales, and is thus also suitable for drawing exponential decays in semilog plots, power laws in loglog plots, etc. However, slope should only be used with linear scales; It has no clear meaning for all other scales, and thus the behavior is undefined. Please specify the line using the points xy1, xy2 for non-linear scales.

The transform keyword argument only applies to the points xy1, xy2. The slope (if given) is always in data coordinates. This can be used e.g. with ax.transAxes for drawing grid lines with a fixed slope.

Parameters
  • xy1 ((float, float)) -- Points for the line to pass through. Either xy2 or slope has to be given.

  • xy2 ((float, float)) -- Points for the line to pass through. Either xy2 or slope has to be given.

  • slope (float, optional) -- The slope of the line. Either xy2 or slope has to be given.

  • **kwargs --

    Valid kwargs are .Line2D properties

    Properties: 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 antialiased or aa: bool clip_box: .Bbox clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color contains: unknown dash_capstyle: .CapStyle or {'butt', 'projecting', 'round'} dash_joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default' figure: .Figure fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'} gid: str in_layout: bool label: object linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: color markeredgewidth or mew: float markerfacecolor or mfc: color markerfacecoloralt or mfcalt: color markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] path_effects: .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {'butt', 'projecting', 'round'} solid_joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} transform: matplotlib.transforms.Transform url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns

Return type

.Line2D

See also

axhline

for horizontal lines

axvline

for vertical lines

Examples

Draw a thick red line passing through (0, 0) and (1, 1):

>>> axline((0, 0), (1, 1), linewidth=4, color='r')
axvline(x=0, ymin=0, ymax=1, **kwargs)[source]

Copy of plt.axvline(). Original docstring is ...

Add a vertical line across the Axes.

Parameters
  • x (float, default: 0) -- x position in data coordinates of the vertical line.

  • ymin (float, default: 0) -- Should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot.

  • ymax (float, default: 1) -- Should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot.

  • **kwargs --

    Valid keyword arguments are .Line2D properties, with the exception of 'transform':

    Properties: 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 antialiased or aa: bool clip_box: .Bbox clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color contains: unknown dash_capstyle: .CapStyle or {'butt', 'projecting', 'round'} dash_joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default' figure: .Figure fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'} gid: str in_layout: bool label: object linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: color markeredgewidth or mew: float markerfacecolor or mfc: color markerfacecoloralt or mfcalt: color markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] path_effects: .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {'butt', 'projecting', 'round'} solid_joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} transform: matplotlib.transforms.Transform url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns

Return type

~matplotlib.lines.Line2D

See also

vlines

Add vertical lines in data coordinates.

axvspan

Add a vertical span (rectangle) across the axis.

axline

Add a line with an arbitrary slope.

Examples

  • draw a thick red vline at x = 0 that spans the yrange:

    >>> axvline(linewidth=4, color='r')
    
  • draw a default vline at x = 1 that spans the yrange:

    >>> axvline(x=1)
    
  • draw a default vline at x = .5 that spans the middle half of the yrange:

    >>> axvline(x=.5, ymin=0.25, ymax=0.75)
    
box(on=None)[source]

Copy of plt.box(). Original docstring is ...

Turn the axes box on or off on the current axes.

Parameters

on (bool or None) -- The new ~matplotlib.axes.Axes box state. If None, toggle the state.

See also

matplotlib.axes.Axes.set_frame_on(), matplotlib.axes.Axes.get_frame_on()

cla()[source]

Copy of plt.cla(). Original docstring is ...

Clear the current axes.

clf()[source]

Copy of plt.clf(). Original docstring is ...

Clear the current figure.

draw()[source]

Copy of plt.draw(). Original docstring is ...

Redraw the current figure.

This is used to update a figure that has been altered, but not automatically re-drawn. If interactive mode is on (via .ion()), this should be only rarely needed, but there may be ways to modify the state of a figure without marking it as "stale". Please report these cases as bugs.

This is equivalent to calling fig.canvas.draw_idle(), where fig is the current figure.

property enabled: bool

toggle interactivity of the figure canvas.

hist(*args, **kwargs)[source]

Copy of plt.hist(). Original docstring is ...

Plot a histogram.

Compute and draw the histogram of x. The return value is a tuple (n, bins, patches) or ([n0, n1, ...], bins, [patches0, patches1, ...]) if the input contains multiple data. See the documentation of the weights parameter to draw a histogram of already-binned data.

Multiple data can be provided via x as a list of datasets of potentially different length ([x0, x1, ...]), or as a 2D ndarray in which each column is a dataset. Note that the ndarray form is transposed relative to the list form.

Masked arrays are not supported.

The bins, range, weights, and density parameters behave as in numpy.histogram.

Parameters
  • x ((n,) array or sequence of (n,) arrays) -- Input values, this takes either a single array or a sequence of arrays which are not required to be of the same length.

  • bins (int or sequence or str, default: :rc:`hist.bins`) --

    If bins is an integer, it defines the number of equal-width bins in the range.

    If bins is a sequence, it defines the bin edges, including the left edge of the first bin and the right edge of the last bin; in this case, bins may be unequally spaced. All but the last (righthand-most) bin is half-open. In other words, if bins is:

    [1, 2, 3, 4]
    

    then the first bin is [1, 2) (including 1, but excluding 2) and the second [2, 3). The last bin, however, is [3, 4], which includes 4.

    If bins is a string, it is one of the binning strategies supported by numpy.histogram_bin_edges: 'auto', 'fd', 'doane', 'scott', 'stone', 'rice', 'sturges', or 'sqrt'.

  • range (tuple or None, default: None) --

    The lower and upper range of the bins. Lower and upper outliers are ignored. If not provided, range is (x.min(), x.max()). Range has no effect if bins is a sequence.

    If bins is a sequence or range is specified, autoscaling is based on the specified bin range instead of the range of x.

  • density (bool, default: False) --

    If True, draw and return a probability density: each bin will display the bin's raw count divided by the total number of counts and the bin width (density = counts / (sum(counts) * np.diff(bins))), so that the area under the histogram integrates to 1 (np.sum(density * np.diff(bins)) == 1).

    If stacked is also True, the sum of the histograms is normalized to 1.

  • weights ((n,) array-like or None, default: None) --

    An array of weights, of the same shape as x. Each value in x only contributes its associated weight towards the bin count (instead of 1). If density is True, the weights are normalized, so that the integral of the density over the range remains 1.

    This parameter can be used to draw a histogram of data that has already been binned, e.g. using numpy.histogram (by treating each bin as a single point with a weight equal to its count)

    counts, bins = np.histogram(data)
    plt.hist(bins[:-1], bins, weights=counts)
    

    (or you may alternatively use ~.bar()).

  • cumulative (bool or -1, default: False) --

    If True, then a histogram is computed where each bin gives the counts in that bin plus all bins for smaller values. The last bin gives the total number of datapoints.

    If density is also True then the histogram is normalized such that the last bin equals 1.

    If cumulative is a number less than 0 (e.g., -1), the direction of accumulation is reversed. In this case, if density is also True, then the histogram is normalized such that the first bin equals 1.

  • bottom (array-like, scalar, or None, default: None) -- Location of the bottom of each bin, ie. bins are drawn from bottom to bottom + hist(x, bins) If a scalar, the bottom of each bin is shifted by the same amount. If an array, each bin is shifted independently and the length of bottom must match the number of bins. If None, defaults to 0.

  • histtype ({'bar', 'barstacked', 'step', 'stepfilled'}, default: 'bar') --

    The type of histogram to draw.

    • 'bar' is a traditional bar-type histogram. If multiple data are given the bars are arranged side by side.

    • 'barstacked' is a bar-type histogram where multiple data are stacked on top of each other.

    • 'step' generates a lineplot that is by default unfilled.

    • 'stepfilled' generates a lineplot that is by default filled.

  • align ({'left', 'mid', 'right'}, default: 'mid') --

    The horizontal alignment of the histogram bars.

    • 'left': bars are centered on the left bin edges.

    • 'mid': bars are centered between the bin edges.

    • 'right': bars are centered on the right bin edges.

  • orientation ({'vertical', 'horizontal'}, default: 'vertical') -- If 'horizontal', ~.Axes.barh will be used for bar-type histograms and the bottom kwarg will be the left edges.

  • rwidth (float or None, default: None) --

    The relative width of the bars as a fraction of the bin width. If None, automatically compute the width.

    Ignored if histtype is 'step' or 'stepfilled'.

  • log (bool, default: False) -- If True, the histogram axis will be set to a log scale.

  • color (color or array-like of colors or None, default: None) -- Color or sequence of colors, one per dataset. Default (None) uses the standard line color sequence.

  • label (str or None, default: None) -- String, or sequence of strings to match multiple datasets. Bar charts yield multiple patches per dataset, but only the first gets the label, so that ~.Axes.legend will work as expected.

  • stacked (bool, default: False) -- If True, multiple data are stacked on top of each other If False multiple data are arranged side by side if histtype is 'bar' or on top of each other if histtype is 'step'

  • **kwargs -- ~matplotlib.patches.Patch properties

Returns

  • n (array or list of arrays) -- The values of the histogram bins. See density and weights for a description of the possible semantics. If input x is an array, then this is an array of length nbins. If input is a sequence of arrays [data1, data2, ...], then this is a list of arrays with the values of the histograms for each of the arrays in the same order. The dtype of the array n (or of its element arrays) will always be float even if no weighting or normalization is used.

  • bins (array) -- The edges of the bins. Length nbins + 1 (nbins left edges and right edge of last bin). Always a single array even when multiple data sets are passed in.

  • patches (.BarContainer or list of a single .Polygon or list of such objects) -- Container of individual artists used to create the histogram or list of such containers if there are multiple input datasets.

See also

hist2d

2D histograms

Notes

For large numbers of bins (>1000), 'step' and 'stepfilled' can be significantly faster than 'bar' and 'barstacked'.

Note

In addition to the above described arguments, this function can take a data keyword argument. If such a data argument is given, the following arguments can also be string s, which is interpreted as data[s] (unless this raises an exception): x, weights.

Objects passed as data must support item access (data[s]) and membership test (s in data).

imshow(*args, **kwargs)[source]

Copy of plt.imshow(). Original docstring is ...

Display data as an image, i.e., on a 2D regular raster.

The input may either be actual RGB(A) data, or 2D scalar data, which will be rendered as a pseudocolor image. For displaying a grayscale image set up the colormapping using the parameters cmap='gray', vmin=0, vmax=255.

The number of pixels used to render an image is set by the Axes size and the dpi of the figure. This can lead to aliasing artifacts when the image is resampled because the displayed image size will usually not match the size of X (see /gallery/images_contours_and_fields/image_antialiasing). The resampling can be controlled via the interpolation parameter and/or :rc:`image.interpolation`.

Parameters
  • X (array-like or PIL image) --

    The image data. Supported array shapes are:

    • (M, N): an image with scalar data. The values are mapped to colors using normalization and a colormap. See parameters norm, cmap, vmin, vmax.

    • (M, N, 3): an image with RGB values (0-1 float or 0-255 int).

    • (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), i.e. including transparency.

    The first two dimensions (M, N) define the rows and columns of the image.

    Out-of-range RGB(A) values are clipped.

  • cmap (str or ~matplotlib.colors.Colormap, default: :rc:`image.cmap`) -- The Colormap instance or registered colormap name used to map scalar data to colors. This parameter is ignored for RGB(A) data.

  • norm (~matplotlib.colors.Normalize, optional) -- The .Normalize instance used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling mapping the lowest value to 0 and the highest to 1 is used. This parameter is ignored for RGB(A) data.

  • aspect ({'equal', 'auto'} or float, default: :rc:`image.aspect`) --

    The aspect ratio of the Axes. This parameter is particularly relevant for images since it determines whether data pixels are square.

    This parameter is a shortcut for explicitly calling .Axes.set_aspect. See there for further details.

    • 'equal': Ensures an aspect ratio of 1. Pixels will be square (unless pixel sizes are explicitly made non-square in data coordinates using extent).

    • 'auto': The Axes is kept fixed and the aspect is adjusted so that the data fit in the Axes. In general, this will result in non-square pixels.

  • interpolation (str, default: :rc:`image.interpolation`) --

    The interpolation method used.

    Supported values are 'none', 'antialiased', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', 'blackman'.

    If interpolation is 'none', then no interpolation is performed on the Agg, ps, pdf and svg backends. Other backends will fall back to 'nearest'. Note that most SVG renderers perform interpolation at rendering and that the default interpolation method they implement may differ.

    If interpolation is the default 'antialiased', then 'nearest' interpolation is used if the image is upsampled by more than a factor of three (i.e. the number of display pixels is at least three times the size of the data array). If the upsampling rate is smaller than 3, or the image is downsampled, then 'hanning' interpolation is used to act as an anti-aliasing filter, unless the image happens to be upsampled by exactly a factor of two or one.

    See /gallery/images_contours_and_fields/interpolation_methods for an overview of the supported interpolation methods, and /gallery/images_contours_and_fields/image_antialiasing for a discussion of image antialiasing.

    Some interpolation methods require an additional radius parameter, which can be set by filterrad. Additionally, the antigrain image resize filter is controlled by the parameter filternorm.

  • alpha (float or array-like, optional) -- The alpha blending value, between 0 (transparent) and 1 (opaque). If alpha is an array, the alpha blending values are applied pixel by pixel, and alpha must have the same shape as X.

  • vmin (float, optional) -- When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is deprecated to use vmin/vmax when norm is given. When using RGB(A) data, parameters vmin/vmax are ignored.

  • vmax (float, optional) -- When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is deprecated to use vmin/vmax when norm is given. When using RGB(A) data, parameters vmin/vmax are ignored.

  • origin ({'upper', 'lower'}, default: :rc:`image.origin`) --

    Place the [0, 0] index of the array in the upper left or lower left corner of the Axes. The convention (the default) 'upper' is typically used for matrices and images.

    Note that the vertical axis points upward for 'lower' but downward for 'upper'.

    See the /tutorials/intermediate/imshow_extent tutorial for examples and a more detailed description.

  • extent (floats (left, right, bottom, top), optional) --

    The bounding box in data coordinates that the image will fill. The image is stretched individually along x and y to fill the box.

    The default extent is determined by the following conditions. Pixels have unit size in data coordinates. Their centers are on integer coordinates, and their center coordinates range from 0 to columns-1 horizontally and from 0 to rows-1 vertically.

    Note that the direction of the vertical axis and thus the default values for top and bottom depend on origin:

    • For origin == 'upper' the default is (-0.5, numcols-0.5, numrows-0.5, -0.5).

    • For origin == 'lower' the default is (-0.5, numcols-0.5, -0.5, numrows-0.5).

    See the /tutorials/intermediate/imshow_extent tutorial for examples and a more detailed description.

  • filternorm (bool, default: True) -- A parameter for the antigrain image resize filter (see the antigrain documentation). If filternorm is set, the filter normalizes integer values and corrects the rounding errors. It doesn't do anything with the source floating point values, it corrects only integers according to the rule of 1.0 which means that any sum of pixel weights must be equal to 1.0. So, the filter function must produce a graph of the proper shape.

  • filterrad (float > 0, default: 4.0) -- The filter radius for filters that have a radius parameter, i.e. when interpolation is one of: 'sinc', 'lanczos' or 'blackman'.

  • resample (bool, default: :rc:`image.resample`) -- When True, use a full resampling method. When False, only resample when the output image is larger than the input image.

  • url (str, optional) -- Set the url of the created .AxesImage. See .Artist.set_url.

  • **kwargs (~matplotlib.artist.Artist properties) -- These parameters are passed on to the constructor of the .AxesImage artist.

Returns

Return type

~matplotlib.image.AxesImage

See also

matshow

Plot a matrix or an array as an image.

Notes

Unless extent is used, pixel centers will be located at integer coordinates. In other words: the origin will coincide with the center of pixel (0, 0).

There are two common representations for RGB images with an alpha channel:

  • Straight (unassociated) alpha: R, G, and B channels represent the color of the pixel, disregarding its opacity.

  • Premultiplied (associated) alpha: R, G, and B channels represent the color of the pixel, adjusted for its opacity by multiplication.

~matplotlib.pyplot.imshow expects RGB images adopting the straight (unassociated) alpha representation.

Note

In addition to the above described arguments, this function can take a data keyword argument. If such a data argument is given, every other argument can also be string s, which is interpreted as data[s] (unless this raises an exception).

Objects passed as data must support item access (data[s]) and membership test (s in data).

property interactive: bool

toggle interactivity of the figure canvas.

legend(*args, **kwargs)[source]

Copy of plt.legend(). Original docstring is ...

Place a legend on the Axes.

Call signatures:

legend()
legend(labels)
legend(handles, labels)

The call signatures correspond to these three 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')
ax.legend()

or:

line, = ax.plot([1, 2, 3])
line.set_label('Label via method')
ax.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 .Axes.legend without any arguments and without setting the labels manually will result in no legend being drawn.

2. Labeling existing plot elements

To make a legend for lines which already exist on the Axes (via plot for instance), simply call this function with an iterable of strings, one for each legend item. For example:

ax.plot([1, 2, 3])
ax.legend(['A simple line'])

Note: 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.

3. Explicitly defining the elements 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:

ax.legend([line1, line2, line3], ['label1', 'label2', 'label3'])
Parameters
  • handles (sequence 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.

  • labels (list 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.

  • loc (str or pair of floats, default: :rc:`legend.loc` ('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_anchor (.BboxBase, 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)
    

  • ncol (int, default: 1) -- The number of columns that the legend has.

  • prop (None or matplotlib.font_manager.FontProperties or dict) -- The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.

  • fontsize (int 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.

  • labelcolor (str or list) -- 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').

  • numpoints (int, default: :rc:`legend.numpoints`) -- The number of marker points in the legend when creating a legend entry for a .Line2D (line).

  • scatterpoints (int, default: :rc:`legend.scatterpoints`) -- The number of marker points in the legend when creating a legend entry for a .PathCollection (scatter plot).

  • scatteryoffsets (iterable 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].

  • markerscale (float, default: :rc:`legend.markerscale`) -- The relative size of legend markers compared with the originally drawn ones.

  • markerfirst (bool, 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.

  • frameon (bool, default: :rc:`legend.frameon`) -- Whether the legend should be drawn on a patch (frame).

  • fancybox (bool, default: :rc:`legend.fancybox`) -- Whether round edges should be enabled around the ~.FancyBboxPatch which makes up the legend's background.

  • shadow (bool, default: :rc:`legend.shadow`) -- Whether to draw a shadow behind the legend.

  • framealpha (float, default: :rc:`legend.framealpha`) -- 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: :rc:`legend.facecolor`) -- The legend's background color. If "inherit", use :rc:`axes.facecolor`.

  • edgecolor ("inherit" or color, default: :rc:`legend.edgecolor`) -- The legend's background patch edge color. If "inherit", use take :rc:`axes.edgecolor`.

  • 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_transform (None 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.

  • title (str or None) -- The legend's title. Default is no title (None).

  • title_fontsize (int or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}, default: :rc:`legend.title_fontsize`) -- The font size of the legend's title.

  • borderpad (float, default: :rc:`legend.borderpad`) -- The fractional whitespace inside the legend border, in font-size units.

  • labelspacing (float, default: :rc:`legend.labelspacing`) -- The vertical space between the legend entries, in font-size units.

  • handlelength (float, default: :rc:`legend.handlelength`) -- The length of the legend handles, in font-size units.

  • handletextpad (float, default: :rc:`legend.handletextpad`) -- The pad between the legend handle and text, in font-size units.

  • borderaxespad (float, default: :rc:`legend.borderaxespad`) -- The pad between the axes and legend border, in font-size units.

  • columnspacing (float, default: :rc:`legend.columnspacing`) -- The spacing between columns, in font-size units.

  • handler_map (dict 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.

Returns

Return type

~matplotlib.legend.Legend

See also

Figure.legend

Notes

Some artists are not supported by this function. See /tutorials/intermediate/legend_guide for details.

Examples

property mouse_click_callbacks: list[typing.Callable]
plot(*args, **kwargs)[source]

Copy of plt.plot(). Original docstring is ...

Plot y versus x as lines and/or markers.

Call signatures:

plot([x], y, [fmt], *, data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)

The coordinates of the points or line nodes are given by x, y.

The optional parameter fmt is a convenient way for defining basic formatting like color, marker and linestyle. It's a shortcut string notation described in the Notes section below.

>>> plot(x, y)        # plot x and y using default line style and color
>>> plot(x, y, 'bo')  # plot x and y using blue circle markers
>>> plot(y)           # plot y using x as index array 0..N-1
>>> plot(y, 'r+')     # ditto, but with red plusses

You can use .Line2D properties as keyword arguments for more control on the appearance. Line properties and fmt can be mixed. The following two calls yield identical results:

>>> plot(x, y, 'go--', linewidth=2, markersize=12)
>>> plot(x, y, color='green', marker='o', linestyle='dashed',
...      linewidth=2, markersize=12)

When conflicting with fmt, keyword arguments take precedence.

Plotting labelled data

There's a convenient way for plotting objects with labelled data (i.e. data that can be accessed by index obj['y']). Instead of giving the data in x and y, you can provide the object in the data parameter and just give the labels for x and y:

>>> plot('xlabel', 'ylabel', data=obj)

All indexable objects are supported. This could e.g. be a dict, a pandas.DataFrame or a structured numpy array.

Plotting multiple sets of data

There are various ways to plot multiple sets of data.

  • The most straight forward way is just to call plot multiple times. Example:

    >>> plot(x1, y1, 'bo')
    >>> plot(x2, y2, 'go')
    
  • If x and/or y are 2D arrays a separate data set will be drawn for every column. If both x and y are 2D, they must have the same shape. If only one of them is 2D with shape (N, m) the other must have length N and will be used for every data set m.

    Example:

    >>> x = [1, 2, 3]
    >>> y = np.array([[1, 2], [3, 4], [5, 6]])
    >>> plot(x, y)
    

    is equivalent to:

    >>> for col in range(y.shape[1]):
    ...     plot(x, y[:, col])
    
  • The third way is to specify multiple sets of [x], y, [fmt] groups:

    >>> plot(x1, y1, 'g^', x2, y2, 'g-')
    

    In this case, any additional keyword argument applies to all datasets. Also this syntax cannot be combined with the data parameter.

By default, each line is assigned a different style specified by a 'style cycle'. The fmt and line property parameters are only necessary if you want explicit deviations from these defaults. Alternatively, you can also change the style cycle using :rc:`axes.prop_cycle`.

Parameters
  • x (array-like or scalar) --

    The horizontal / vertical coordinates of the data points. x values are optional and default to range(len(y)).

    Commonly, these parameters are 1D arrays.

    They can also be scalars, or two-dimensional (in that case, the columns represent separate data sets).

    These arguments cannot be passed as keywords.

  • y (array-like or scalar) --

    The horizontal / vertical coordinates of the data points. x values are optional and default to range(len(y)).

    Commonly, these parameters are 1D arrays.

    They can also be scalars, or two-dimensional (in that case, the columns represent separate data sets).

    These arguments cannot be passed as keywords.

  • fmt (str, optional) --

    A format string, e.g. 'ro' for red circles. See the Notes section for a full description of the format strings.

    Format strings are just an abbreviation for quickly setting basic line properties. All of these and more can also be controlled by keyword arguments.

    This argument cannot be passed as keyword.

  • data (indexable object, optional) --

    An object with labelled data. If given, provide the label names to plot in x and y.

    Note

    Technically there's a slight ambiguity in calls where the second label is a valid fmt. plot('n', 'o', data=obj) could be plt(x, y) or plt(y, fmt). In such cases, the former interpretation is chosen, but a warning is issued. You may suppress the warning by adding an empty format string plot('n', 'o', '', data=obj).

  • scalex (bool, default: True) -- These parameters determine if the view limits are adapted to the data limits. The values are passed on to autoscale_view.

  • scaley (bool, default: True) -- These parameters determine if the view limits are adapted to the data limits. The values are passed on to autoscale_view.

  • **kwargs (.Line2D properties, optional) --

    kwargs are used to specify properties like a line label (for auto legends), linewidth, antialiasing, marker face color. Example:

    >>> plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2)
    >>> plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2')
    

    If you specify multiple lines with one plot call, the kwargs apply to all those lines. In case the label object is iterable, each element is used as labels for each set of data.

    Here is a list of available .Line2D properties:

    Properties: 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 antialiased or aa: bool clip_box: .Bbox clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color contains: unknown dash_capstyle: .CapStyle or {'butt', 'projecting', 'round'} dash_joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default' figure: .Figure fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'} gid: str in_layout: bool label: object linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: color markeredgewidth or mew: float markerfacecolor or mfc: color markerfacecoloralt or mfcalt: color markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] path_effects: .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {'butt', 'projecting', 'round'} solid_joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} transform: matplotlib.transforms.Transform url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns

A list of lines representing the plotted data.

Return type

list of .Line2D

See also

scatter

XY scatter plot with markers of varying size and/or color ( sometimes also called bubble chart).

Notes

Format Strings

A format string consists of a part for color, marker and line:

fmt = '[marker][line][color]'

Each of them is optional. If not provided, the value from the style cycle is used. Exception: If line is given, but no marker, the data will be a line without markers.

Other combinations such as [color][marker][line] are also supported, but note that their parsing may be ambiguous.

Markers

character

description

'.'

point marker

','

pixel marker

'o'

circle marker

'v'

triangle_down marker

'^'

triangle_up marker

'<'

triangle_left marker

'>'

triangle_right marker

'1'

tri_down marker

'2'

tri_up marker

'3'

tri_left marker

'4'

tri_right marker

'8'

octagon marker

's'

square marker

'p'

pentagon marker

'P'

plus (filled) marker

'*'

star marker

'h'

hexagon1 marker

'H'

hexagon2 marker

'+'

plus marker

'x'

x marker

'X'

x (filled) marker

'D'

diamond marker

'd'

thin_diamond marker

'|'

vline marker

'_'

hline marker

Line Styles

character

description

'-'

solid line style

'--'

dashed line style

'-.'

dash-dot line style

':'

dotted line style

Example format strings:

'b'    # blue markers with default shape
'or'   # red circles
'-g'   # green solid line
'--'   # dashed line with default color
'^k:'  # black triangle_up markers connected by a dotted line

Colors

The supported color abbreviations are the single letter codes

character

color

'b'

blue

'g'

green

'r'

red

'c'

cyan

'm'

magenta

'y'

yellow

'k'

black

'w'

white

and the 'CN' colors that index into the default property cycle.

If the color is the only part of the format string, you can additionally use any matplotlib.colors spec, e.g. full names ('green') or hex strings ('#008000').

quiver(*args, data=None, **kwargs)[source]

Copy of plt.quiver(). Original docstring is ...

Plot a 2D field of arrows.

Call signature:

quiver([X, Y], U, V, [C], **kw)

X, Y define the arrow locations, U, V define the arrow directions, and C optionally sets the color.

Arrow size

The default settings auto-scales the length of the arrows to a reasonable size. To change this behavior see the scale and scale_units parameters.

Arrow shape

The defaults give a slightly swept-back arrow; to make the head a triangle, make headaxislength the same as headlength. To make the arrow more pointed, reduce headwidth or increase headlength and headaxislength. To make the head smaller relative to the shaft, scale down all the head parameters. You will probably do best to leave minshaft alone.

Arrow outline

linewidths and edgecolors can be used to customize the arrow outlines.

Parameters
  • X (1D or 2D array-like, optional) --

    The x and y coordinates of the arrow locations.

    If not given, they will be generated as a uniform integer meshgrid based on the dimensions of U and V.

    If X and Y are 1D but U, V are 2D, X, Y are expanded to 2D using X, Y = np.meshgrid(X, Y). In this case len(X) and len(Y) must match the column and row dimensions of U and V.

  • Y (1D or 2D array-like, optional) --

    The x and y coordinates of the arrow locations.

    If not given, they will be generated as a uniform integer meshgrid based on the dimensions of U and V.

    If X and Y are 1D but U, V are 2D, X, Y are expanded to 2D using X, Y = np.meshgrid(X, Y). In this case len(X) and len(Y) must match the column and row dimensions of U and V.

  • U (1D or 2D array-like) --

    The x and y direction components of the arrow vectors.

    They must have the same number of elements, matching the number of arrow locations. U and V may be masked. Only locations unmasked in U, V, and C will be drawn.

  • V (1D or 2D array-like) --

    The x and y direction components of the arrow vectors.

    They must have the same number of elements, matching the number of arrow locations. U and V may be masked. Only locations unmasked in U, V, and C will be drawn.

  • C (1D or 2D array-like, optional) --

    Numeric data that defines the arrow colors by colormapping via norm and cmap.

    This does not support explicit colors. If you want to set colors directly, use color instead. The size of C must match the number of arrow locations.

  • units ({'width', 'height', 'dots', 'inches', 'x', 'y', 'xy'}, default: 'width') --

    The arrow dimensions (except for length) are measured in multiples of this unit.

    The following values are supported:

    • 'width', 'height': The width or height of the axis.

    • 'dots', 'inches': Pixels or inches based on the figure dpi.

    • 'x', 'y', 'xy': X, Y or \(\sqrt{X^2 + Y^2}\) in data units.

    The arrows scale differently depending on the units. For 'x' or 'y', the arrows get larger as one zooms in; for other units, the arrow size is independent of the zoom state. For 'width or 'height', the arrow size increases with the width and height of the axes, respectively, when the window is resized; for 'dots' or 'inches', resizing does not change the arrows.

  • angles ({'uv', 'xy'} or array-like, default: 'uv') --

    Method for determining the angle of the arrows.

    • 'uv': The arrow axis aspect ratio is 1 so that if U == V the orientation of the arrow on the plot is 45 degrees counter-clockwise from the horizontal axis (positive to the right).

      Use this if the arrows symbolize a quantity that is not based on X, Y data coordinates.

    • 'xy': Arrows point from (x, y) to (x+u, y+v). Use this for plotting a gradient field, for example.

    • Alternatively, arbitrary angles may be specified explicitly as an array of values in degrees, counter-clockwise from the horizontal axis.

      In this case U, V is only used to determine the length of the arrows.

    Note: inverting a data axis will correspondingly invert the arrows only with angles='xy'.

  • scale (float, optional) --

    Number of data units per arrow length unit, e.g., m/s per plot width; a smaller scale parameter makes the arrow longer. Default is None.

    If None, a simple autoscaling algorithm is used, based on the average vector length and the number of vectors. The arrow length unit is given by the scale_units parameter.

  • scale_units ({'width', 'height', 'dots', 'inches', 'x', 'y', 'xy'}, optional) --

    If the scale kwarg is None, the arrow length unit. Default is None.

    e.g. scale_units is 'inches', scale is 2.0, and (u, v) = (1, 0), then the vector will be 0.5 inches long.

    If scale_units is 'width' or 'height', then the vector will be half the width/height of the axes.

    If scale_units is 'x' then the vector will be 0.5 x-axis units. To plot vectors in the x-y plane, with u and v having the same units as x and y, use angles='xy', scale_units='xy', scale=1.

  • width (float, optional) -- Shaft width in arrow units; default depends on choice of units, above, and number of vectors; a typical starting value is about 0.005 times the width of the plot.

  • headwidth (float, default: 3) -- Head width as multiple of shaft width.

  • headlength (float, default: 5) -- Head length as multiple of shaft width.

  • headaxislength (float, default: 4.5) -- Head length at shaft intersection.

  • minshaft (float, default: 1) -- Length below which arrow scales, in units of head length. Do not set this to less than 1, or small arrows will look terrible!

  • minlength (float, default: 1) -- Minimum length as a multiple of shaft width; if an arrow length is less than this, plot a dot (hexagon) of this diameter instead.

  • pivot ({'tail', 'mid', 'middle', 'tip'}, default: 'tail') --

    The part of the arrow that is anchored to the X, Y grid. The arrow rotates about this point.

    'mid' is a synonym for 'middle'.

  • color (color or color sequence, optional) --

    Explicit color(s) for the arrows. If C has been set, color has no effect.

    This is a synonym for the ~.PolyCollection facecolor parameter.

  • **kwargs (~matplotlib.collections.PolyCollection properties, optional) --

    All other keyword arguments are passed on to .PolyCollection:

    Properties: 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: array-like or scalar or None animated: bool antialiased or aa or antialiaseds: bool or list of bools array: ndarray or None capstyle: .CapStyle or {'butt', 'projecting', 'round'} clim: (vmin: float, vmax: float) clip_box: .Bbox clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: color or list of rgba tuples contains: unknown edgecolor or ec or edgecolors: color or list of colors or 'face' facecolor or facecolors or fc: color or list of colors figure: .Figure gid: str hatch: {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'} in_layout: bool joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} label: object linestyle or dashes or linestyles or ls: str or tuple or list thereof linewidth or linewidths or lw: float or list of floats norm: .Normalize or None offset_position: unknown offsets: (N, 2) or (2,) array-like path_effects: .AbstractPathEffect picker: None or bool or float or callable pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: .Transform url: str urls: list of str or None visible: bool zorder: float

See also

Axes.quiverkey

Add a key to a quiver plot.

savefig(*args, **kwargs)[source]

Copy of plt.savefig(). Original docstring is ...

Save the current figure.

Call signature:

savefig(fname, dpi=None, facecolor='w', edgecolor='w',
        orientation='portrait', papertype=None, format=None,
        transparent=False, bbox_inches=None, pad_inches=0.1,
        frameon=None, metadata=None)

The available output formats depend on the backend being used.

Parameters
  • fname (str or path-like or binary file-like) --

    A path, or a Python file-like object, or possibly some backend-dependent object such as matplotlib.backends.backend_pdf.PdfPages.

    If format is set, it determines the output format, and the file is saved as fname. Note that fname is used verbatim, and there is no attempt to make the extension, if any, of fname match format, and no extension is appended.

    If format is not set, then the format is inferred from the extension of fname, if there is one. If format is not set and fname has no extension, then the file is saved with :rc:`savefig.format` and the appropriate extension is appended to fname.

  • dpi (float or 'figure', default: :rc:`savefig.dpi`) -- The resolution in dots per inch. If 'figure', use the figure's dpi value.

  • quality (int, default: :rc:`savefig.jpeg_quality`) --

    Applicable only if format is 'jpg' or 'jpeg', ignored otherwise.

    The image quality, on a scale from 1 (worst) to 95 (best). Values above 95 should be avoided; 100 disables portions of the JPEG compression algorithm, and results in large files with hardly any gain in image quality.

    This parameter is deprecated.

  • optimize (bool, default: False) --

    Applicable only if format is 'jpg' or 'jpeg', ignored otherwise.

    Whether the encoder should make an extra pass over the image in order to select optimal encoder settings.

    This parameter is deprecated.

  • progressive (bool, default: False) --

    Applicable only if format is 'jpg' or 'jpeg', ignored otherwise.

    Whether the image should be stored as a progressive JPEG file.

    This parameter is deprecated.

  • facecolor (color or 'auto', default: :rc:`savefig.facecolor`) -- The facecolor of the figure. If 'auto', use the current figure facecolor.

  • edgecolor (color or 'auto', default: :rc:`savefig.edgecolor`) -- The edgecolor of the figure. If 'auto', use the current figure edgecolor.

  • orientation ({'landscape', 'portrait'}) -- Currently only supported by the postscript backend.

  • papertype (str) -- One of 'letter', 'legal', 'executive', 'ledger', 'a0' through 'a10', 'b0' through 'b10'. Only supported for postscript output.

  • format (str) -- The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this is unset is documented under fname.

  • transparent (bool) -- If True, the Axes patches will all be transparent; the figure patch will also be transparent unless facecolor and/or edgecolor are specified via kwargs. This is useful, for example, for displaying a plot on top of a colored background on a web page. The transparency of these patches will be restored to their original values upon exit of this function.

  • bbox_inches (str or .Bbox, default: :rc:`savefig.bbox`) -- Bounding box in inches: only the given portion of the figure is saved. If 'tight', try to figure out the tight bbox of the figure.

  • pad_inches (float, default: :rc:`savefig.pad_inches`) -- Amount of padding around the figure when bbox_inches is 'tight'.

  • bbox_extra_artists (list of ~matplotlib.artist.Artist, optional) -- A list of extra artists that will be considered when the tight bbox is calculated.

  • backend (str, optional) -- Use a non-default backend to render the file, e.g. to render a png file with the "cairo" backend rather than the default "agg", or a pdf file with the "pgf" backend rather than the default "pdf". Note that the default backend is normally sufficient. See the-builtin-backends for a list of valid backends for each file format. Custom backends can be referenced as "module://...".

  • metadata (dict, optional) --

    Key/value pairs to store in the image metadata. The supported keys and defaults depend on the image format and backend:

    • 'png' with Agg backend: See the parameter metadata of ~.FigureCanvasAgg.print_png.

    • 'pdf' with pdf backend: See the parameter metadata of ~.backend_pdf.PdfPages.

    • 'svg' with svg backend: See the parameter metadata of ~.FigureCanvasSVG.print_svg.

    • 'eps' and 'ps' with PS backend: Only 'Creator' is supported.

  • pil_kwargs (dict, optional) -- Additional keyword arguments that are passed to PIL.Image.Image.save when saving the figure.

scatter(*args, **kwargs)[source]

Copy of plt.scatter(). Original docstring is ...

A scatter plot of y vs. x with varying marker size and/or color.

Parameters
  • x (float or array-like, shape (n, )) -- The data positions.

  • y (float or array-like, shape (n, )) -- The data positions.

  • s (float or array-like, shape (n, ), optional) -- The marker size in points**2. Default is rcParams['lines.markersize'] ** 2.

  • c (array-like or list of colors or color, optional) --

    The marker colors. Possible values:

    • A scalar or sequence of n numbers to be mapped to colors using cmap and norm.

    • A 2D array in which the rows are RGB or RGBA.

    • A sequence of colors of length n.

    • A single color format string.

    Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. If you want to specify the same RGB or RGBA value for all points, use a 2D array with a single row. Otherwise, value- matching will have precedence in case of a size matching with x and y.

    If you wish to specify a single color for all points prefer the color keyword argument.

    Defaults to None. In that case the marker color is determined by the value of color, facecolor or facecolors. In case those are not specified or None, the marker color is determined by the next color of the Axes' current "shape and fill" color cycle. This cycle defaults to :rc:`axes.prop_cycle`.

  • marker (~.markers.MarkerStyle, default: :rc:`scatter.marker`) -- The marker style. marker can be either an instance of the class or the text shorthand for a particular marker. See matplotlib.markers for more information about marker styles.

  • cmap (str or ~matplotlib.colors.Colormap, default: :rc:`image.cmap`) -- A .Colormap instance or registered colormap name. cmap is only used if c is an array of floats.

  • norm (~matplotlib.colors.Normalize, default: None) -- If c is an array of floats, norm is used to scale the color data, c, in the range 0 to 1, in order to map into the colormap cmap. If None, use the default .colors.Normalize.

  • vmin (float, default: None) -- vmin and vmax are used in conjunction with the default norm to map the color array c to the colormap cmap. If None, the respective min and max of the color array is used. It is deprecated to use vmin/vmax when norm is given.

  • vmax (float, default: None) -- vmin and vmax are used in conjunction with the default norm to map the color array c to the colormap cmap. If None, the respective min and max of the color array is used. It is deprecated to use vmin/vmax when norm is given.

  • alpha (float, default: None) -- The alpha blending value, between 0 (transparent) and 1 (opaque).

  • linewidths (float or array-like, default: :rc:`lines.linewidth`) -- The linewidth of the marker edges. Note: The default edgecolors is 'face'. You may want to change this as well.

  • edgecolors ({'face', 'none', None} or color or sequence of color, default: :rc:`scatter.edgecolors`) --

    The edge color of the marker. Possible values:

    • 'face': The edge color will always be the same as the face color.

    • 'none': No patch boundary will be drawn.

    • A color or sequence of colors.

    For non-filled markers, edgecolors is ignored. Instead, the color is determined like with 'face', i.e. from c, colors, or facecolors.

  • plotnonfinite (bool, default: False) -- Whether to plot points with nonfinite c (i.e. inf, -inf or nan). If True the points are drawn with the bad colormap color (see .Colormap.set_bad).

  • **kwargs (~matplotlib.collections.Collection properties) --

Returns

Return type

~matplotlib.collections.PathCollection

See also

plot

To plot scatter plots when markers are identical in size and color.

Notes

  • The .plot function will be faster for scatterplots where markers don't vary in size or color.

  • Any or all of x, y, s, and c may be masked arrays, in which case all masks will be combined and only unmasked points will be plotted.

  • Fundamentally, scatter works with 1D arrays; x, y, s, and c may be input as N-D arrays, but within scatter they will be flattened. The exception is c, which will be flattened only if its size matches the size of x and y.

Note

In addition to the above described arguments, this function can take a data keyword argument. If such a data argument is given, the following arguments can also be string s, which is interpreted as data[s] (unless this raises an exception): x, y, s, linewidths, edgecolors, c, facecolor, facecolors, color.

Objects passed as data must support item access (data[s]) and membership test (s in data).

subplots(*args, **kwargs)[source]

Copy of plt.subplots(). Original docstring is ...

Create a figure and a set of subplots.

This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call.

Parameters
  • nrows (int, default: 1) -- Number of rows/columns of the subplot grid.

  • ncols (int, default: 1) -- Number of rows/columns of the subplot grid.

  • sharex (bool or {'none', 'all', 'row', 'col'}, default: False) --

    Controls sharing of properties among x (sharex) or y (sharey) axes:

    • 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 ~matplotlib.axes.Axes.tick_params.

    When subplots have a shared axis that has units, calling ~matplotlib.axis.Axis.set_units will update each axis with the new units.

  • sharey (bool or {'none', 'all', 'row', 'col'}, default: False) --

    Controls sharing of properties among x (sharex) or y (sharey) axes:

    • 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 ~matplotlib.axes.Axes.tick_params.

    When subplots have a shared axis that has units, calling ~matplotlib.axis.Axis.set_units will update each axis with the new units.

  • squeeze (bool, default: True) --

    • If True, extra dimensions are squeezed out from the returned array of ~matplotlib.axes.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_kw (dict, optional) -- Dict with keywords passed to the ~matplotlib.figure.Figure.add_subplot call used to create each subplot.

  • gridspec_kw (dict, optional) -- Dict with keywords passed to the ~matplotlib.gridspec.GridSpec constructor used to create the grid the subplots are placed on.

  • **fig_kw -- All additional keyword arguments are passed to the .pyplot.figure call.

Returns

  • fig (~.figure.Figure)

  • ax (.axes.Axes or array of Axes) -- ax can be either a single ~matplotlib.axes.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.

    Typical idioms for handling the return value are:

    # using the variable ax for single a Axes
    fig, ax = plt.subplots()
    
    # using the variable axs for multiple Axes
    fig, axs = plt.subplots(2, 2)
    
    # using tuple unpacking for multiple Axes
    fig, (ax1, ax2) = plt.subplots(1, 2)
    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
    

    The names ax and pluralized axs are preferred over axes because for the latter it's not clear if it refers to a single ~.axes.Axes instance or a collection of these.

See also

pyplot.figure, pyplot.subplot, pyplot.axes, Figure.subplots, Figure.add_subplot

Examples

# First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

# Create just a figure and only one subplot
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')

# Create two subplots and unpack the output array immediately
f, (ax1, ax2) = plt.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
fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar"))
axs[0, 0].plot(x, y)
axs[1, 1].scatter(x, y)

# Share a X axis with each column of subplots
plt.subplots(2, 2, sharex='col')

# Share a Y axis with each row of subplots
plt.subplots(2, 2, sharey='row')

# Share both X and Y axes with all subplots
plt.subplots(2, 2, sharex='all', sharey='all')

# Note that this is the same as
plt.subplots(2, 2, sharex=True, sharey=True)

# Create figure number 10 with a single subplot
# and clears it if it already exists.
fig, ax = plt.subplots(num=10, clear=True)
text(*args, **kwargs)[source]

Copy of plt.text(). Original docstring is ...

Add text to the Axes.

Add the text s to the Axes at location x, y in data coordinates.

Parameters
  • x (float) -- The position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the transform parameter.

  • y (float) -- The position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the transform parameter.

  • s (str) -- The text.

  • fontdict (dict, default: None) -- A dictionary to override the default text properties. If fontdict is None, the defaults are determined by .rcParams.

  • **kwargs (~matplotlib.text.Text properties.) --

    Other miscellaneous text parameters.

    Properties: 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: .Bbox clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color contains: unknown 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'} 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

Returns

The created .Text instance.

Return type

.Text

Examples

Individual keyword arguments can be used to override any given parameter:

>>> text(x, y, s, fontsize=12)

The default transform specifies that text is in data coords, alternatively, you can specify text in axis coords ((0, 0) is lower-left and (1, 1) is upper-right). The example below places text in the center of the Axes:

>>> text(0.5, 0.5, 'matplotlib', horizontalalignment='center',
...      verticalalignment='center', transform=ax.transAxes)

You can put a rectangular box around the text instance (e.g., to set a background color) by using the keyword bbox. bbox is a dictionary of ~matplotlib.patches.Rectangle properties. For example:

>>> text(x, y, s, bbox=dict(facecolor='red', alpha=0.5))
title(*args, **kwargs)[source]

Copy of plt.title(). Original docstring is ...

Set a title for the Axes.

Set one of the three available Axes titles. The available titles are positioned above the Axes in the center, flush with the left edge, and flush with the right edge.

Parameters
  • label (str) -- Text to use for the title

  • fontdict (dict) --

    A dictionary controlling the appearance of the title text, the default fontdict is:

    {'fontsize': rcParams['axes.titlesize'],
     'fontweight': rcParams['axes.titleweight'],
     'color': rcParams['axes.titlecolor'],
     'verticalalignment': 'baseline',
     'horizontalalignment': loc}
    

  • loc ({'center', 'left', 'right'}, default: :rc:`axes.titlelocation`) -- Which title to set.

  • y (float, default: :rc:`axes.titley`) -- Vertical Axes loation for the title (1.0 is the top). If None (the default), y is determined automatically to avoid decorators on the Axes.

  • pad (float, default: :rc:`axes.titlepad`) -- The offset of the title from the top of the Axes, in points.

  • **kwargs (.Text properties) -- Other keyword arguments are text properties, see .Text for a list of valid text properties.

Returns

The matplotlib text instance representing the title

Return type

.Text

twinx()[source]

Copy of plt.twinx(). Original docstring is ...

Make and return a second axes that shares the x-axis. The new axes will overlay ax (or the current axes if ax is None), and its ticks will be on the right.

Examples

/gallery/subplots_axes_and_figures/two_scales

twiny()[source]

Copy of plt.twiny(). Original docstring is ...

Make and return a second axes that shares the y-axis. The new axes will overlay ax (or the current axes if ax is None), and its ticks will be on the top.

Examples

/gallery/subplots_axes_and_figures/two_scales

xlabel(*args, **kwargs)[source]

Copy of plt.xlabel(). Original docstring is ...

Set the label for the x-axis.

Parameters
  • xlabel (str) -- The label text.

  • labelpad (float, default: :rc:`axes.labelpad`) -- Spacing in points from the axes bounding box including ticks and tick labels. If None, the previous value is left as is.

  • loc ({'left', 'center', 'right'}, default: :rc:`xaxis.labellocation`) -- The label position. This is a high-level alternative for passing parameters x and horizontalalignment.

  • **kwargs (.Text properties) -- .Text properties control the appearance of the label.

See also

text

Documents the properties supported by .Text.

xlim(*args, **kwargs)[source]

Copy of plt.xlim(). Original docstring is ...

Get or set the x limits of the current axes.

Call signatures:

left, right = xlim()  # return the current xlim
xlim((left, right))   # set the xlim to left, right
xlim(left, right)     # set the xlim to left, right

If you do not specify args, you can pass left or right as kwargs, i.e.:

xlim(right=3)  # adjust the right leaving left unchanged
xlim(left=1)  # adjust the left leaving right unchanged

Setting limits turns autoscaling off for the x-axis.

Returns

A tuple of the new x-axis limits.

Return type

left, right

Notes

Calling this function with no arguments (e.g. xlim()) is the pyplot equivalent of calling ~.Axes.get_xlim on the current axes. Calling this function with arguments is the pyplot equivalent of calling ~.Axes.set_xlim on the current axes. All arguments are passed though.

xscale(scale=None)[source]

Copy of plt.xscale(). Original docstring is ...

Set the x-axis scale.

Parameters
  • value ({"linear", "log", "symlog", "logit", ...} or .ScaleBase) -- The axis scale type to apply.

  • **kwargs --

    Different keyword arguments are accepted, depending on the scale. See the respective class keyword arguments:

    • matplotlib.scale.LinearScale

    • matplotlib.scale.LogScale

    • matplotlib.scale.SymmetricalLogScale

    • matplotlib.scale.LogitScale

    • matplotlib.scale.FuncScale

Notes

By default, Matplotlib supports the above mentioned scales. Additionally, custom scales may be registered using matplotlib.scale.register_scale. These scales can then also be used here.

xticks(ticks=None, labels=None, **kwargs)[source]

Copy of plt.xticks(). Original docstring is ...

Get or set the current tick locations and labels of the x-axis.

Pass no arguments to return the current values without modifying them.

Parameters
  • ticks (array-like, optional) -- The list of xtick locations. Passing an empty list removes all xticks.

  • labels (array-like, optional) -- The labels to place at the given ticks locations. This argument can only be passed if ticks is passed as well.

  • **kwargs -- .Text properties can be used to control the appearance of the labels.

Returns

  • locs -- The list of xtick locations.

  • labels -- The list of xlabel .Text objects.

Notes

Calling this function with no arguments (e.g. xticks()) is the pyplot equivalent of calling ~.Axes.get_xticks and ~.Axes.get_xticklabels on the current axes. Calling this function with arguments is the pyplot equivalent of calling ~.Axes.set_xticks and ~.Axes.set_xticklabels on the current axes.

Examples

>>> locs, labels = xticks()  # Get the current locations and labels.
>>> xticks(np.arange(0, 1, step=0.2))  # Set label locations.
>>> xticks(np.arange(3), ['Tom', 'Dick', 'Sue'])  # Set text labels.
>>> xticks([0, 1, 2], ['January', 'February', 'March'],
...        rotation=20)  # Set text labels and properties.
>>> xticks([])  # Disable xticks.
ylabel(*args, **kwargs)[source]

Copy of plt.ylabel(). Original docstring is ...

Set the label for the y-axis.

Parameters
  • ylabel (str) -- The label text.

  • labelpad (float, default: :rc:`axes.labelpad`) -- Spacing in points from the axes bounding box including ticks and tick labels. If None, the previous value is left as is.

  • loc ({'bottom', 'center', 'top'}, default: :rc:`yaxis.labellocation`) -- The label position. This is a high-level alternative for passing parameters y and horizontalalignment.

  • **kwargs (.Text properties) -- .Text properties control the appearance of the label.

See also

text

Documents the properties supported by .Text.

ylim(*args, **kwargs)[source]

Copy of plt.ylim(). Original docstring is ...

Get or set the y-limits of the current axes.

Call signatures:

bottom, top = ylim()  # return the current ylim
ylim((bottom, top))   # set the ylim to bottom, top
ylim(bottom, top)     # set the ylim to bottom, top

If you do not specify args, you can alternatively pass bottom or top as kwargs, i.e.:

ylim(top=3)  # adjust the top leaving bottom unchanged
ylim(bottom=1)  # adjust the bottom leaving top unchanged

Setting limits turns autoscaling off for the y-axis.

Returns

A tuple of the new y-axis limits.

Return type

bottom, top

Notes

Calling this function with no arguments (e.g. ylim()) is the pyplot equivalent of calling ~.Axes.get_ylim on the current axes. Calling this function with arguments is the pyplot equivalent of calling ~.Axes.set_ylim on the current axes. All arguments are passed though.

yscale(scale=None)[source]

Copy of plt.yscale(). Original docstring is ...

Set the y-axis scale.

Parameters
  • value ({"linear", "log", "symlog", "logit", ...} or .ScaleBase) -- The axis scale type to apply.

  • **kwargs --

    Different keyword arguments are accepted, depending on the scale. See the respective class keyword arguments:

    • matplotlib.scale.LinearScale

    • matplotlib.scale.LogScale

    • matplotlib.scale.SymmetricalLogScale

    • matplotlib.scale.LogitScale

    • matplotlib.scale.FuncScale

Notes

By default, Matplotlib supports the above mentioned scales. Additionally, custom scales may be registered using matplotlib.scale.register_scale. These scales can then also be used here.

yticks(ticks=None, labels=None, **kwargs)[source]

Copy of plt.yticks(). Original docstring is ...

Get or set the current tick locations and labels of the y-axis.

Pass no arguments to return the current values without modifying them.

Parameters
  • ticks (array-like, optional) -- The list of ytick locations. Passing an empty list removes all yticks.

  • labels (array-like, optional) -- The labels to place at the given ticks locations. This argument can only be passed if ticks is passed as well.

  • **kwargs -- .Text properties can be used to control the appearance of the labels.

Returns

  • locs -- The list of ytick locations.

  • labels -- The list of ylabel .Text objects.

Notes

Calling this function with no arguments (e.g. yticks()) is the pyplot equivalent of calling ~.Axes.get_yticks and ~.Axes.get_yticklabels on the current axes. Calling this function with arguments is the pyplot equivalent of calling ~.Axes.set_yticks and ~.Axes.set_yticklabels on the current axes.

Examples

>>> locs, labels = yticks()  # Get the current locations and labels.
>>> yticks(np.arange(0, 1, step=0.2))  # Set label locations.
>>> yticks(np.arange(3), ['Tom', 'Dick', 'Sue'])  # Set text labels.
>>> yticks([0, 1, 2], ['January', 'February', 'March'],
...        rotation=45)  # Set text labels and properties.
>>> yticks([])  # Disable yticks.
class magicclass.widgets.misc.FloatEdit(value=UNSET, **kwargs)[source]

Bases: magicgui.widgets.LineEdit

class magicclass.widgets.misc.FloatRangeSlider(value=UNSET, min=0, max=1000, orientation: str = 'horizontal', nullable: bool = True, **kwargs)[source]

Bases: magicclass.widgets.misc.AbstractRangeSlider[float]

name: str
class magicclass.widgets.misc.IntEdit(value=UNSET, **kwargs)[source]

Bases: magicgui.widgets.LineEdit

class magicclass.widgets.misc.QFloatEdit[source]

Bases: magicgui.backends._qtpy.widgets.LineEdit

class magicclass.widgets.misc.QIntEdit[source]

Bases: magicgui.backends._qtpy.widgets.LineEdit

class magicclass.widgets.misc.QRangeSlider(qwidg: PyQt5.QtWidgets.QWidget)[source]

Bases: magicgui.backends._qtpy.widgets.QBaseWidget

class magicclass.widgets.misc.RangeSlider(value=UNSET, min=0, max=1000, orientation: str = 'horizontal', nullable: bool = True, **kwargs)[source]

Bases: magicclass.widgets.misc.AbstractRangeSlider[int]

name: str
class magicclass.widgets.misc.SpreadSheet[source]

Bases: magicclass.widgets.utils.FreeWidget, MutableSequence[magicgui.widgets._table.Table]

A simple spread sheet widget.

index(value[, start[, stop]]) integer -- return first index of value.[source]

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

insert(key: int, value)[source]

S.insert(index, value) -- insert value before index

rename(index: int, name: str)[source]

magicclass.widgets.separator module

class magicclass.widgets.separator.Separator(orientation: str = 'horizontal', text: str = '', name: str = '', button: bool = False)[source]

Bases: magicclass.widgets.utils.FreeWidget

A Separator widget that can be used in both widgets and menus. This widget is not actually added to menus or toolbars.

btn_clicked

Signal descriptor, for declaring a signal on a class.

This is designed to be used as a class attribute, with the supported signature(s) provided in the contructor:

class MyEmitter:

changed = Signal(int) # changed will emit an int

def receiver(arg: int):

print("new value:", arg)

emitter = MyEmitter() emitter.changed.connect(receiver) emitter.emit(1)

Note: in the example above, MyEmitter.changed is an instance of Signal, and emitter.changed is an instance of SignalInstance.

Parameters
  • *types (sequence of Type) -- A sequence of individual types

  • description (str, optional) -- Optional descriptive text for the signal. (not used internally).

  • name (str, optional) -- Optional name of the signal. If it is not specified then the name of the class attribute that is bound to the signal will be used. default None

  • check_nargs_on_connect (str, optional) -- Whether to check the number of positional args against signature when connecting a new callback. This can also be provided at connection time using .connect(..., check_nargs=True). By default, True.

  • check_types_on_connect (str, optional) -- Whether to check the callback parameter types against signature when connecting a new callback. This can also be provided at connection time using .connect(..., check_types=True). By default, False.

property btn_text

magicclass.widgets.sequence module

class magicclass.widgets.sequence.ListDataView(obj: magicgui.widgets.ListEdit)[source]

Bases: object

Data view of ListEdit.

magicclass.widgets.utils module

class magicclass.widgets.utils.FreeWidget(layout='vertical', **kwargs)[source]

Bases: magicgui.widgets._bases.widget.Widget

A Widget class with any QWidget as a child.

set_contextmenu(contextmenugui: ContextMenuGui)[source]
set_widget(widget: PyQt5.QtWidgets.QWidget, *args)[source]

Set the central widget to the widget.

magicclass.widgets.utils.merge_super_sigs(cls)[source]

Module contents

Advanced widgets for magic class GUI. These widgets are all compatible with the append method of Container widgets.

class magicclass.widgets.ButtonContainer(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, layout: str = 'vertical', widgets: Sequence[Widget] = (), labels=True)

Bases: magicgui.widgets._bases.widget.Widget, magicgui.widgets._bases.mixins._OrientationMixin, MutableSequence[magicgui.widgets._bases.widget.Widget]

A Container Widget hidden in a button.

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

property btn_text
property text
class magicclass.widgets.CheckButton(text: str | None = None, **kwargs)[source]

Bases: magicgui.widgets.PushButton

A checkable button.

class magicclass.widgets.CollapsibleContainer(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, layout: str = 'vertical', widgets: Sequence[Widget] = (), labels=True)

Bases: magicgui.widgets._bases.widget.Widget, magicgui.widgets._bases.mixins._OrientationMixin, MutableSequence[magicgui.widgets._bases.widget.Widget]

A collapsible Container Widget.

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

property btn_text
property collapsed: bool
property text
class magicclass.widgets.ColorEdit(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, value: Any = UNSET, bind: Any = UNSET, nullable=False)

Bases: magicgui.widgets._bases.value_widget.ValueWidget

A widget for editing colors.

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

  • value (tuple of float or str) -- The starting value for the widget.

  • bind (Any) -- A value or callback to bind this widget, then whenever widget.value is accessed, the value provided here will be returned. value can be a callable, in which case value(self) will be returned (i.e. your callback must accept a single parameter, which is this widget instance.).

  • value -- RGBA color, color code or standard color name.

class magicclass.widgets.ColorSlider(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, value: Any = UNSET, bind: Any = UNSET, nullable=False)

Bases: magicgui.widgets._bases.value_widget.ValueWidget

A multi-slider for editing colors.

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

  • value (tuple of float or str) -- The starting value for the widget.

  • bind (Any) -- A value or callback to bind this widget, then whenever widget.value is accessed, the value provided here will be returned. value can be a callable, in which case value(self) will be returned (i.e. your callback must accept a single parameter, which is this widget instance.).

  • value -- RGBA color, color code or standard color name.

class magicclass.widgets.ConsoleTextEdit(*args, **kwargs)[source]

Bases: magicgui.widgets.TextEdit

A text edit with console-like setting.

append(text: str)[source]

Append new text.

erase_first()[source]

Erase the first line.

erase_last()[source]

Erase the last line.

property selected: str

Return selected string.

property tab_size
class magicclass.widgets.DictWidget(value=None, **kwargs)[source]

Bases: magicclass.widgets.pywidgets.object.BaseWidget, MutableMapping

clear() None[source]

Clear dictionary contents.

get(k[, d]) D[k] if k in D, else d.  d defaults to None.[source]
items() magicclass.widgets.pywidgets.dict.DictItemView[source]

Return the view of dictionary keys and values as strings and Python objects.

keys()[source]

Return the view of dictionary keys.

pop(k: str)[source]

Pop a dictionary content.

update(d: dict[str, typing.Any])[source]

Update the dictionary contents.

property value: dict[str, typing.Any]
values() magicclass.widgets.pywidgets.dict.DictValueView[source]

Return the view of dictionary values as Python objects.

class magicclass.widgets.DraggableContainer(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, layout: str = 'vertical', widgets: Sequence[Widget] = (), labels=True)

Bases: magicgui.widgets._bases.widget.Widget, magicgui.widgets._bases.mixins._OrientationMixin, MutableSequence[magicgui.widgets._bases.widget.Widget]

A draggable Container Widget.

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

class magicclass.widgets.Figure(nrows: int = 1, ncols: int = 1, figsize: tuple[float, float] = (4.0, 3.0), style=None, **kwargs)[source]

Bases: magicclass.widgets.utils.FreeWidget

A matplotlib figure canvas.

autoscale(enable=True, axis='both', tight=None)[source]

Copy of plt.autoscale(). Original docstring is ...

Autoscale the axis view to the data (toggle).

Convenience method for simple axis view autoscaling. It turns autoscaling on or off, and then, if autoscaling for either axis is on, it performs the autoscaling on the specified axis or axes.

Parameters
  • enable (bool or None, default: True) -- True turns autoscaling on, False turns it off. None leaves the autoscaling state unchanged.

  • axis ({'both', 'x', 'y'}, default: 'both') -- Which axis to operate on.

  • tight (bool or None, default: None) -- If True, first set the margins to zero. Then, this argument is forwarded to autoscale_view (regardless of its value); see the description of its behavior there.

property ax: Axes

The first matplotlib axis.

property axes: list[Axes]

List of matplotlib axes.

axhline(y=0, xmin=0, xmax=1, **kwargs)[source]

Copy of plt.axhline(). Original docstring is ...

Add a horizontal line across the axis.

Parameters
  • y (float, default: 0) -- y position in data coordinates of the horizontal line.

  • xmin (float, default: 0) -- Should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot.

  • xmax (float, default: 1) -- Should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot.

  • **kwargs --

    Valid keyword arguments are .Line2D properties, with the exception of 'transform':

    Properties: 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 antialiased or aa: bool clip_box: .Bbox clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color contains: unknown dash_capstyle: .CapStyle or {'butt', 'projecting', 'round'} dash_joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default' figure: .Figure fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'} gid: str in_layout: bool label: object linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: color markeredgewidth or mew: float markerfacecolor or mfc: color markerfacecoloralt or mfcalt: color markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] path_effects: .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {'butt', 'projecting', 'round'} solid_joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} transform: matplotlib.transforms.Transform url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns

Return type

~matplotlib.lines.Line2D

See also

hlines

Add horizontal lines in data coordinates.

axhspan

Add a horizontal span (rectangle) across the axis.

axline

Add a line with an arbitrary slope.

Examples

  • draw a thick red hline at 'y' = 0 that spans the xrange:

    >>> axhline(linewidth=4, color='r')
    
  • draw a default hline at 'y' = 1 that spans the xrange:

    >>> axhline(y=1)
    
  • draw a default hline at 'y' = .5 that spans the middle half of the xrange:

    >>> axhline(y=.5, xmin=0.25, xmax=0.75)
    
axline(xy1, xy2=None, *, slope=None, **kwargs)[source]

Copy of plt.axline(). Original docstring is ...

Add an infinitely long straight line.

The line can be defined either by two points xy1 and xy2, or by one point xy1 and a slope.

This draws a straight line "on the screen", regardless of the x and y scales, and is thus also suitable for drawing exponential decays in semilog plots, power laws in loglog plots, etc. However, slope should only be used with linear scales; It has no clear meaning for all other scales, and thus the behavior is undefined. Please specify the line using the points xy1, xy2 for non-linear scales.

The transform keyword argument only applies to the points xy1, xy2. The slope (if given) is always in data coordinates. This can be used e.g. with ax.transAxes for drawing grid lines with a fixed slope.

Parameters
  • xy1 ((float, float)) -- Points for the line to pass through. Either xy2 or slope has to be given.

  • xy2 ((float, float)) -- Points for the line to pass through. Either xy2 or slope has to be given.

  • slope (float, optional) -- The slope of the line. Either xy2 or slope has to be given.

  • **kwargs --

    Valid kwargs are .Line2D properties

    Properties: 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 antialiased or aa: bool clip_box: .Bbox clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color contains: unknown dash_capstyle: .CapStyle or {'butt', 'projecting', 'round'} dash_joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default' figure: .Figure fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'} gid: str in_layout: bool label: object linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: color markeredgewidth or mew: float markerfacecolor or mfc: color markerfacecoloralt or mfcalt: color markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] path_effects: .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {'butt', 'projecting', 'round'} solid_joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} transform: matplotlib.transforms.Transform url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns

Return type

.Line2D

See also

axhline

for horizontal lines

axvline

for vertical lines

Examples

Draw a thick red line passing through (0, 0) and (1, 1):

>>> axline((0, 0), (1, 1), linewidth=4, color='r')
axvline(x=0, ymin=0, ymax=1, **kwargs)[source]

Copy of plt.axvline(). Original docstring is ...

Add a vertical line across the Axes.

Parameters
  • x (float, default: 0) -- x position in data coordinates of the vertical line.

  • ymin (float, default: 0) -- Should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot.

  • ymax (float, default: 1) -- Should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot.

  • **kwargs --

    Valid keyword arguments are .Line2D properties, with the exception of 'transform':

    Properties: 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 antialiased or aa: bool clip_box: .Bbox clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color contains: unknown dash_capstyle: .CapStyle or {'butt', 'projecting', 'round'} dash_joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default' figure: .Figure fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'} gid: str in_layout: bool label: object linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: color markeredgewidth or mew: float markerfacecolor or mfc: color markerfacecoloralt or mfcalt: color markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] path_effects: .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {'butt', 'projecting', 'round'} solid_joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} transform: matplotlib.transforms.Transform url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns

Return type

~matplotlib.lines.Line2D

See also

vlines

Add vertical lines in data coordinates.

axvspan

Add a vertical span (rectangle) across the axis.

axline

Add a line with an arbitrary slope.

Examples

  • draw a thick red vline at x = 0 that spans the yrange:

    >>> axvline(linewidth=4, color='r')
    
  • draw a default vline at x = 1 that spans the yrange:

    >>> axvline(x=1)
    
  • draw a default vline at x = .5 that spans the middle half of the yrange:

    >>> axvline(x=.5, ymin=0.25, ymax=0.75)
    
box(on=None)[source]

Copy of plt.box(). Original docstring is ...

Turn the axes box on or off on the current axes.

Parameters

on (bool or None) -- The new ~matplotlib.axes.Axes box state. If None, toggle the state.

See also

matplotlib.axes.Axes.set_frame_on(), matplotlib.axes.Axes.get_frame_on()

cla()[source]

Copy of plt.cla(). Original docstring is ...

Clear the current axes.

clf()[source]

Copy of plt.clf(). Original docstring is ...

Clear the current figure.

draw()[source]

Copy of plt.draw(). Original docstring is ...

Redraw the current figure.

This is used to update a figure that has been altered, but not automatically re-drawn. If interactive mode is on (via .ion()), this should be only rarely needed, but there may be ways to modify the state of a figure without marking it as "stale". Please report these cases as bugs.

This is equivalent to calling fig.canvas.draw_idle(), where fig is the current figure.

property enabled: bool

toggle interactivity of the figure canvas.

hist(*args, **kwargs)[source]

Copy of plt.hist(). Original docstring is ...

Plot a histogram.

Compute and draw the histogram of x. The return value is a tuple (n, bins, patches) or ([n0, n1, ...], bins, [patches0, patches1, ...]) if the input contains multiple data. See the documentation of the weights parameter to draw a histogram of already-binned data.

Multiple data can be provided via x as a list of datasets of potentially different length ([x0, x1, ...]), or as a 2D ndarray in which each column is a dataset. Note that the ndarray form is transposed relative to the list form.

Masked arrays are not supported.

The bins, range, weights, and density parameters behave as in numpy.histogram.

Parameters
  • x ((n,) array or sequence of (n,) arrays) -- Input values, this takes either a single array or a sequence of arrays which are not required to be of the same length.

  • bins (int or sequence or str, default: :rc:`hist.bins`) --

    If bins is an integer, it defines the number of equal-width bins in the range.

    If bins is a sequence, it defines the bin edges, including the left edge of the first bin and the right edge of the last bin; in this case, bins may be unequally spaced. All but the last (righthand-most) bin is half-open. In other words, if bins is:

    [1, 2, 3, 4]
    

    then the first bin is [1, 2) (including 1, but excluding 2) and the second [2, 3). The last bin, however, is [3, 4], which includes 4.

    If bins is a string, it is one of the binning strategies supported by numpy.histogram_bin_edges: 'auto', 'fd', 'doane', 'scott', 'stone', 'rice', 'sturges', or 'sqrt'.

  • range (tuple or None, default: None) --

    The lower and upper range of the bins. Lower and upper outliers are ignored. If not provided, range is (x.min(), x.max()). Range has no effect if bins is a sequence.

    If bins is a sequence or range is specified, autoscaling is based on the specified bin range instead of the range of x.

  • density (bool, default: False) --

    If True, draw and return a probability density: each bin will display the bin's raw count divided by the total number of counts and the bin width (density = counts / (sum(counts) * np.diff(bins))), so that the area under the histogram integrates to 1 (np.sum(density * np.diff(bins)) == 1).

    If stacked is also True, the sum of the histograms is normalized to 1.

  • weights ((n,) array-like or None, default: None) --

    An array of weights, of the same shape as x. Each value in x only contributes its associated weight towards the bin count (instead of 1). If density is True, the weights are normalized, so that the integral of the density over the range remains 1.

    This parameter can be used to draw a histogram of data that has already been binned, e.g. using numpy.histogram (by treating each bin as a single point with a weight equal to its count)

    counts, bins = np.histogram(data)
    plt.hist(bins[:-1], bins, weights=counts)
    

    (or you may alternatively use ~.bar()).

  • cumulative (bool or -1, default: False) --

    If True, then a histogram is computed where each bin gives the counts in that bin plus all bins for smaller values. The last bin gives the total number of datapoints.

    If density is also True then the histogram is normalized such that the last bin equals 1.

    If cumulative is a number less than 0 (e.g., -1), the direction of accumulation is reversed. In this case, if density is also True, then the histogram is normalized such that the first bin equals 1.

  • bottom (array-like, scalar, or None, default: None) -- Location of the bottom of each bin, ie. bins are drawn from bottom to bottom + hist(x, bins) If a scalar, the bottom of each bin is shifted by the same amount. If an array, each bin is shifted independently and the length of bottom must match the number of bins. If None, defaults to 0.

  • histtype ({'bar', 'barstacked', 'step', 'stepfilled'}, default: 'bar') --

    The type of histogram to draw.

    • 'bar' is a traditional bar-type histogram. If multiple data are given the bars are arranged side by side.

    • 'barstacked' is a bar-type histogram where multiple data are stacked on top of each other.

    • 'step' generates a lineplot that is by default unfilled.

    • 'stepfilled' generates a lineplot that is by default filled.

  • align ({'left', 'mid', 'right'}, default: 'mid') --

    The horizontal alignment of the histogram bars.

    • 'left': bars are centered on the left bin edges.

    • 'mid': bars are centered between the bin edges.

    • 'right': bars are centered on the right bin edges.

  • orientation ({'vertical', 'horizontal'}, default: 'vertical') -- If 'horizontal', ~.Axes.barh will be used for bar-type histograms and the bottom kwarg will be the left edges.

  • rwidth (float or None, default: None) --

    The relative width of the bars as a fraction of the bin width. If None, automatically compute the width.

    Ignored if histtype is 'step' or 'stepfilled'.

  • log (bool, default: False) -- If True, the histogram axis will be set to a log scale.

  • color (color or array-like of colors or None, default: None) -- Color or sequence of colors, one per dataset. Default (None) uses the standard line color sequence.

  • label (str or None, default: None) -- String, or sequence of strings to match multiple datasets. Bar charts yield multiple patches per dataset, but only the first gets the label, so that ~.Axes.legend will work as expected.

  • stacked (bool, default: False) -- If True, multiple data are stacked on top of each other If False multiple data are arranged side by side if histtype is 'bar' or on top of each other if histtype is 'step'

  • **kwargs -- ~matplotlib.patches.Patch properties

Returns

  • n (array or list of arrays) -- The values of the histogram bins. See density and weights for a description of the possible semantics. If input x is an array, then this is an array of length nbins. If input is a sequence of arrays [data1, data2, ...], then this is a list of arrays with the values of the histograms for each of the arrays in the same order. The dtype of the array n (or of its element arrays) will always be float even if no weighting or normalization is used.

  • bins (array) -- The edges of the bins. Length nbins + 1 (nbins left edges and right edge of last bin). Always a single array even when multiple data sets are passed in.

  • patches (.BarContainer or list of a single .Polygon or list of such objects) -- Container of individual artists used to create the histogram or list of such containers if there are multiple input datasets.

See also

hist2d

2D histograms

Notes

For large numbers of bins (>1000), 'step' and 'stepfilled' can be significantly faster than 'bar' and 'barstacked'.

Note

In addition to the above described arguments, this function can take a data keyword argument. If such a data argument is given, the following arguments can also be string s, which is interpreted as data[s] (unless this raises an exception): x, weights.

Objects passed as data must support item access (data[s]) and membership test (s in data).

imshow(*args, **kwargs)[source]

Copy of plt.imshow(). Original docstring is ...

Display data as an image, i.e., on a 2D regular raster.

The input may either be actual RGB(A) data, or 2D scalar data, which will be rendered as a pseudocolor image. For displaying a grayscale image set up the colormapping using the parameters cmap='gray', vmin=0, vmax=255.

The number of pixels used to render an image is set by the Axes size and the dpi of the figure. This can lead to aliasing artifacts when the image is resampled because the displayed image size will usually not match the size of X (see /gallery/images_contours_and_fields/image_antialiasing). The resampling can be controlled via the interpolation parameter and/or :rc:`image.interpolation`.

Parameters
  • X (array-like or PIL image) --

    The image data. Supported array shapes are:

    • (M, N): an image with scalar data. The values are mapped to colors using normalization and a colormap. See parameters norm, cmap, vmin, vmax.

    • (M, N, 3): an image with RGB values (0-1 float or 0-255 int).

    • (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), i.e. including transparency.

    The first two dimensions (M, N) define the rows and columns of the image.

    Out-of-range RGB(A) values are clipped.

  • cmap (str or ~matplotlib.colors.Colormap, default: :rc:`image.cmap`) -- The Colormap instance or registered colormap name used to map scalar data to colors. This parameter is ignored for RGB(A) data.

  • norm (~matplotlib.colors.Normalize, optional) -- The .Normalize instance used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling mapping the lowest value to 0 and the highest to 1 is used. This parameter is ignored for RGB(A) data.

  • aspect ({'equal', 'auto'} or float, default: :rc:`image.aspect`) --

    The aspect ratio of the Axes. This parameter is particularly relevant for images since it determines whether data pixels are square.

    This parameter is a shortcut for explicitly calling .Axes.set_aspect. See there for further details.

    • 'equal': Ensures an aspect ratio of 1. Pixels will be square (unless pixel sizes are explicitly made non-square in data coordinates using extent).

    • 'auto': The Axes is kept fixed and the aspect is adjusted so that the data fit in the Axes. In general, this will result in non-square pixels.

  • interpolation (str, default: :rc:`image.interpolation`) --

    The interpolation method used.

    Supported values are 'none', 'antialiased', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', 'blackman'.

    If interpolation is 'none', then no interpolation is performed on the Agg, ps, pdf and svg backends. Other backends will fall back to 'nearest'. Note that most SVG renderers perform interpolation at rendering and that the default interpolation method they implement may differ.

    If interpolation is the default 'antialiased', then 'nearest' interpolation is used if the image is upsampled by more than a factor of three (i.e. the number of display pixels is at least three times the size of the data array). If the upsampling rate is smaller than 3, or the image is downsampled, then 'hanning' interpolation is used to act as an anti-aliasing filter, unless the image happens to be upsampled by exactly a factor of two or one.

    See /gallery/images_contours_and_fields/interpolation_methods for an overview of the supported interpolation methods, and /gallery/images_contours_and_fields/image_antialiasing for a discussion of image antialiasing.

    Some interpolation methods require an additional radius parameter, which can be set by filterrad. Additionally, the antigrain image resize filter is controlled by the parameter filternorm.

  • alpha (float or array-like, optional) -- The alpha blending value, between 0 (transparent) and 1 (opaque). If alpha is an array, the alpha blending values are applied pixel by pixel, and alpha must have the same shape as X.

  • vmin (float, optional) -- When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is deprecated to use vmin/vmax when norm is given. When using RGB(A) data, parameters vmin/vmax are ignored.

  • vmax (float, optional) -- When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is deprecated to use vmin/vmax when norm is given. When using RGB(A) data, parameters vmin/vmax are ignored.

  • origin ({'upper', 'lower'}, default: :rc:`image.origin`) --

    Place the [0, 0] index of the array in the upper left or lower left corner of the Axes. The convention (the default) 'upper' is typically used for matrices and images.

    Note that the vertical axis points upward for 'lower' but downward for 'upper'.

    See the /tutorials/intermediate/imshow_extent tutorial for examples and a more detailed description.

  • extent (floats (left, right, bottom, top), optional) --

    The bounding box in data coordinates that the image will fill. The image is stretched individually along x and y to fill the box.

    The default extent is determined by the following conditions. Pixels have unit size in data coordinates. Their centers are on integer coordinates, and their center coordinates range from 0 to columns-1 horizontally and from 0 to rows-1 vertically.

    Note that the direction of the vertical axis and thus the default values for top and bottom depend on origin:

    • For origin == 'upper' the default is (-0.5, numcols-0.5, numrows-0.5, -0.5).

    • For origin == 'lower' the default is (-0.5, numcols-0.5, -0.5, numrows-0.5).

    See the /tutorials/intermediate/imshow_extent tutorial for examples and a more detailed description.

  • filternorm (bool, default: True) -- A parameter for the antigrain image resize filter (see the antigrain documentation). If filternorm is set, the filter normalizes integer values and corrects the rounding errors. It doesn't do anything with the source floating point values, it corrects only integers according to the rule of 1.0 which means that any sum of pixel weights must be equal to 1.0. So, the filter function must produce a graph of the proper shape.

  • filterrad (float > 0, default: 4.0) -- The filter radius for filters that have a radius parameter, i.e. when interpolation is one of: 'sinc', 'lanczos' or 'blackman'.

  • resample (bool, default: :rc:`image.resample`) -- When True, use a full resampling method. When False, only resample when the output image is larger than the input image.

  • url (str, optional) -- Set the url of the created .AxesImage. See .Artist.set_url.

  • **kwargs (~matplotlib.artist.Artist properties) -- These parameters are passed on to the constructor of the .AxesImage artist.

Returns

Return type

~matplotlib.image.AxesImage

See also

matshow

Plot a matrix or an array as an image.

Notes

Unless extent is used, pixel centers will be located at integer coordinates. In other words: the origin will coincide with the center of pixel (0, 0).

There are two common representations for RGB images with an alpha channel:

  • Straight (unassociated) alpha: R, G, and B channels represent the color of the pixel, disregarding its opacity.

  • Premultiplied (associated) alpha: R, G, and B channels represent the color of the pixel, adjusted for its opacity by multiplication.

~matplotlib.pyplot.imshow expects RGB images adopting the straight (unassociated) alpha representation.

Note

In addition to the above described arguments, this function can take a data keyword argument. If such a data argument is given, every other argument can also be string s, which is interpreted as data[s] (unless this raises an exception).

Objects passed as data must support item access (data[s]) and membership test (s in data).

property interactive: bool

toggle interactivity of the figure canvas.

legend(*args, **kwargs)[source]

Copy of plt.legend(). Original docstring is ...

Place a legend on the Axes.

Call signatures:

legend()
legend(labels)
legend(handles, labels)

The call signatures correspond to these three 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')
ax.legend()

or:

line, = ax.plot([1, 2, 3])
line.set_label('Label via method')
ax.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 .Axes.legend without any arguments and without setting the labels manually will result in no legend being drawn.

2. Labeling existing plot elements

To make a legend for lines which already exist on the Axes (via plot for instance), simply call this function with an iterable of strings, one for each legend item. For example:

ax.plot([1, 2, 3])
ax.legend(['A simple line'])

Note: 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.

3. Explicitly defining the elements 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:

ax.legend([line1, line2, line3], ['label1', 'label2', 'label3'])
Parameters
  • handles (sequence 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.

  • labels (list 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.

  • loc (str or pair of floats, default: :rc:`legend.loc` ('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_anchor (.BboxBase, 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)
    

  • ncol (int, default: 1) -- The number of columns that the legend has.

  • prop (None or matplotlib.font_manager.FontProperties or dict) -- The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.

  • fontsize (int 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.

  • labelcolor (str or list) -- 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').

  • numpoints (int, default: :rc:`legend.numpoints`) -- The number of marker points in the legend when creating a legend entry for a .Line2D (line).

  • scatterpoints (int, default: :rc:`legend.scatterpoints`) -- The number of marker points in the legend when creating a legend entry for a .PathCollection (scatter plot).

  • scatteryoffsets (iterable 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].

  • markerscale (float, default: :rc:`legend.markerscale`) -- The relative size of legend markers compared with the originally drawn ones.

  • markerfirst (bool, 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.

  • frameon (bool, default: :rc:`legend.frameon`) -- Whether the legend should be drawn on a patch (frame).

  • fancybox (bool, default: :rc:`legend.fancybox`) -- Whether round edges should be enabled around the ~.FancyBboxPatch which makes up the legend's background.

  • shadow (bool, default: :rc:`legend.shadow`) -- Whether to draw a shadow behind the legend.

  • framealpha (float, default: :rc:`legend.framealpha`) -- 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: :rc:`legend.facecolor`) -- The legend's background color. If "inherit", use :rc:`axes.facecolor`.

  • edgecolor ("inherit" or color, default: :rc:`legend.edgecolor`) -- The legend's background patch edge color. If "inherit", use take :rc:`axes.edgecolor`.

  • 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_transform (None 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.

  • title (str or None) -- The legend's title. Default is no title (None).

  • title_fontsize (int or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}, default: :rc:`legend.title_fontsize`) -- The font size of the legend's title.

  • borderpad (float, default: :rc:`legend.borderpad`) -- The fractional whitespace inside the legend border, in font-size units.

  • labelspacing (float, default: :rc:`legend.labelspacing`) -- The vertical space between the legend entries, in font-size units.

  • handlelength (float, default: :rc:`legend.handlelength`) -- The length of the legend handles, in font-size units.

  • handletextpad (float, default: :rc:`legend.handletextpad`) -- The pad between the legend handle and text, in font-size units.

  • borderaxespad (float, default: :rc:`legend.borderaxespad`) -- The pad between the axes and legend border, in font-size units.

  • columnspacing (float, default: :rc:`legend.columnspacing`) -- The spacing between columns, in font-size units.

  • handler_map (dict 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.

Returns

Return type

~matplotlib.legend.Legend

See also

Figure.legend

Notes

Some artists are not supported by this function. See /tutorials/intermediate/legend_guide for details.

Examples

property mouse_click_callbacks: list[typing.Callable]
plot(*args, **kwargs)[source]

Copy of plt.plot(). Original docstring is ...

Plot y versus x as lines and/or markers.

Call signatures:

plot([x], y, [fmt], *, data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)

The coordinates of the points or line nodes are given by x, y.

The optional parameter fmt is a convenient way for defining basic formatting like color, marker and linestyle. It's a shortcut string notation described in the Notes section below.

>>> plot(x, y)        # plot x and y using default line style and color
>>> plot(x, y, 'bo')  # plot x and y using blue circle markers
>>> plot(y)           # plot y using x as index array 0..N-1
>>> plot(y, 'r+')     # ditto, but with red plusses

You can use .Line2D properties as keyword arguments for more control on the appearance. Line properties and fmt can be mixed. The following two calls yield identical results:

>>> plot(x, y, 'go--', linewidth=2, markersize=12)
>>> plot(x, y, color='green', marker='o', linestyle='dashed',
...      linewidth=2, markersize=12)

When conflicting with fmt, keyword arguments take precedence.

Plotting labelled data

There's a convenient way for plotting objects with labelled data (i.e. data that can be accessed by index obj['y']). Instead of giving the data in x and y, you can provide the object in the data parameter and just give the labels for x and y:

>>> plot('xlabel', 'ylabel', data=obj)

All indexable objects are supported. This could e.g. be a dict, a pandas.DataFrame or a structured numpy array.

Plotting multiple sets of data

There are various ways to plot multiple sets of data.

  • The most straight forward way is just to call plot multiple times. Example:

    >>> plot(x1, y1, 'bo')
    >>> plot(x2, y2, 'go')
    
  • If x and/or y are 2D arrays a separate data set will be drawn for every column. If both x and y are 2D, they must have the same shape. If only one of them is 2D with shape (N, m) the other must have length N and will be used for every data set m.

    Example:

    >>> x = [1, 2, 3]
    >>> y = np.array([[1, 2], [3, 4], [5, 6]])
    >>> plot(x, y)
    

    is equivalent to:

    >>> for col in range(y.shape[1]):
    ...     plot(x, y[:, col])
    
  • The third way is to specify multiple sets of [x], y, [fmt] groups:

    >>> plot(x1, y1, 'g^', x2, y2, 'g-')
    

    In this case, any additional keyword argument applies to all datasets. Also this syntax cannot be combined with the data parameter.

By default, each line is assigned a different style specified by a 'style cycle'. The fmt and line property parameters are only necessary if you want explicit deviations from these defaults. Alternatively, you can also change the style cycle using :rc:`axes.prop_cycle`.

Parameters
  • x (array-like or scalar) --

    The horizontal / vertical coordinates of the data points. x values are optional and default to range(len(y)).

    Commonly, these parameters are 1D arrays.

    They can also be scalars, or two-dimensional (in that case, the columns represent separate data sets).

    These arguments cannot be passed as keywords.

  • y (array-like or scalar) --

    The horizontal / vertical coordinates of the data points. x values are optional and default to range(len(y)).

    Commonly, these parameters are 1D arrays.

    They can also be scalars, or two-dimensional (in that case, the columns represent separate data sets).

    These arguments cannot be passed as keywords.

  • fmt (str, optional) --

    A format string, e.g. 'ro' for red circles. See the Notes section for a full description of the format strings.

    Format strings are just an abbreviation for quickly setting basic line properties. All of these and more can also be controlled by keyword arguments.

    This argument cannot be passed as keyword.

  • data (indexable object, optional) --

    An object with labelled data. If given, provide the label names to plot in x and y.

    Note

    Technically there's a slight ambiguity in calls where the second label is a valid fmt. plot('n', 'o', data=obj) could be plt(x, y) or plt(y, fmt). In such cases, the former interpretation is chosen, but a warning is issued. You may suppress the warning by adding an empty format string plot('n', 'o', '', data=obj).

  • scalex (bool, default: True) -- These parameters determine if the view limits are adapted to the data limits. The values are passed on to autoscale_view.

  • scaley (bool, default: True) -- These parameters determine if the view limits are adapted to the data limits. The values are passed on to autoscale_view.

  • **kwargs (.Line2D properties, optional) --

    kwargs are used to specify properties like a line label (for auto legends), linewidth, antialiasing, marker face color. Example:

    >>> plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2)
    >>> plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2')
    

    If you specify multiple lines with one plot call, the kwargs apply to all those lines. In case the label object is iterable, each element is used as labels for each set of data.

    Here is a list of available .Line2D properties:

    Properties: 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 antialiased or aa: bool clip_box: .Bbox clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color contains: unknown dash_capstyle: .CapStyle or {'butt', 'projecting', 'round'} dash_joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default' figure: .Figure fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'} gid: str in_layout: bool label: object linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: color markeredgewidth or mew: float markerfacecolor or mfc: color markerfacecoloralt or mfcalt: color markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] path_effects: .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {'butt', 'projecting', 'round'} solid_joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} transform: matplotlib.transforms.Transform url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns

A list of lines representing the plotted data.

Return type

list of .Line2D

See also

scatter

XY scatter plot with markers of varying size and/or color ( sometimes also called bubble chart).

Notes

Format Strings

A format string consists of a part for color, marker and line:

fmt = '[marker][line][color]'

Each of them is optional. If not provided, the value from the style cycle is used. Exception: If line is given, but no marker, the data will be a line without markers.

Other combinations such as [color][marker][line] are also supported, but note that their parsing may be ambiguous.

Markers

character

description

'.'

point marker

','

pixel marker

'o'

circle marker

'v'

triangle_down marker

'^'

triangle_up marker

'<'

triangle_left marker

'>'

triangle_right marker

'1'

tri_down marker

'2'

tri_up marker

'3'

tri_left marker

'4'

tri_right marker

'8'

octagon marker

's'

square marker

'p'

pentagon marker

'P'

plus (filled) marker

'*'

star marker

'h'

hexagon1 marker

'H'

hexagon2 marker

'+'

plus marker

'x'

x marker

'X'

x (filled) marker

'D'

diamond marker

'd'

thin_diamond marker

'|'

vline marker

'_'

hline marker

Line Styles

character

description

'-'

solid line style

'--'

dashed line style

'-.'

dash-dot line style

':'

dotted line style

Example format strings:

'b'    # blue markers with default shape
'or'   # red circles
'-g'   # green solid line
'--'   # dashed line with default color
'^k:'  # black triangle_up markers connected by a dotted line

Colors

The supported color abbreviations are the single letter codes

character

color

'b'

blue

'g'

green

'r'

red

'c'

cyan

'm'

magenta

'y'

yellow

'k'

black

'w'

white

and the 'CN' colors that index into the default property cycle.

If the color is the only part of the format string, you can additionally use any matplotlib.colors spec, e.g. full names ('green') or hex strings ('#008000').

quiver(*args, data=None, **kwargs)[source]

Copy of plt.quiver(). Original docstring is ...

Plot a 2D field of arrows.

Call signature:

quiver([X, Y], U, V, [C], **kw)

X, Y define the arrow locations, U, V define the arrow directions, and C optionally sets the color.

Arrow size

The default settings auto-scales the length of the arrows to a reasonable size. To change this behavior see the scale and scale_units parameters.

Arrow shape

The defaults give a slightly swept-back arrow; to make the head a triangle, make headaxislength the same as headlength. To make the arrow more pointed, reduce headwidth or increase headlength and headaxislength. To make the head smaller relative to the shaft, scale down all the head parameters. You will probably do best to leave minshaft alone.

Arrow outline

linewidths and edgecolors can be used to customize the arrow outlines.

Parameters
  • X (1D or 2D array-like, optional) --

    The x and y coordinates of the arrow locations.

    If not given, they will be generated as a uniform integer meshgrid based on the dimensions of U and V.

    If X and Y are 1D but U, V are 2D, X, Y are expanded to 2D using X, Y = np.meshgrid(X, Y). In this case len(X) and len(Y) must match the column and row dimensions of U and V.

  • Y (1D or 2D array-like, optional) --

    The x and y coordinates of the arrow locations.

    If not given, they will be generated as a uniform integer meshgrid based on the dimensions of U and V.

    If X and Y are 1D but U, V are 2D, X, Y are expanded to 2D using X, Y = np.meshgrid(X, Y). In this case len(X) and len(Y) must match the column and row dimensions of U and V.

  • U (1D or 2D array-like) --

    The x and y direction components of the arrow vectors.

    They must have the same number of elements, matching the number of arrow locations. U and V may be masked. Only locations unmasked in U, V, and C will be drawn.

  • V (1D or 2D array-like) --

    The x and y direction components of the arrow vectors.

    They must have the same number of elements, matching the number of arrow locations. U and V may be masked. Only locations unmasked in U, V, and C will be drawn.

  • C (1D or 2D array-like, optional) --

    Numeric data that defines the arrow colors by colormapping via norm and cmap.

    This does not support explicit colors. If you want to set colors directly, use color instead. The size of C must match the number of arrow locations.

  • units ({'width', 'height', 'dots', 'inches', 'x', 'y', 'xy'}, default: 'width') --

    The arrow dimensions (except for length) are measured in multiples of this unit.

    The following values are supported:

    • 'width', 'height': The width or height of the axis.

    • 'dots', 'inches': Pixels or inches based on the figure dpi.

    • 'x', 'y', 'xy': X, Y or \(\sqrt{X^2 + Y^2}\) in data units.

    The arrows scale differently depending on the units. For 'x' or 'y', the arrows get larger as one zooms in; for other units, the arrow size is independent of the zoom state. For 'width or 'height', the arrow size increases with the width and height of the axes, respectively, when the window is resized; for 'dots' or 'inches', resizing does not change the arrows.

  • angles ({'uv', 'xy'} or array-like, default: 'uv') --

    Method for determining the angle of the arrows.

    • 'uv': The arrow axis aspect ratio is 1 so that if U == V the orientation of the arrow on the plot is 45 degrees counter-clockwise from the horizontal axis (positive to the right).

      Use this if the arrows symbolize a quantity that is not based on X, Y data coordinates.

    • 'xy': Arrows point from (x, y) to (x+u, y+v). Use this for plotting a gradient field, for example.

    • Alternatively, arbitrary angles may be specified explicitly as an array of values in degrees, counter-clockwise from the horizontal axis.

      In this case U, V is only used to determine the length of the arrows.

    Note: inverting a data axis will correspondingly invert the arrows only with angles='xy'.

  • scale (float, optional) --

    Number of data units per arrow length unit, e.g., m/s per plot width; a smaller scale parameter makes the arrow longer. Default is None.

    If None, a simple autoscaling algorithm is used, based on the average vector length and the number of vectors. The arrow length unit is given by the scale_units parameter.

  • scale_units ({'width', 'height', 'dots', 'inches', 'x', 'y', 'xy'}, optional) --

    If the scale kwarg is None, the arrow length unit. Default is None.

    e.g. scale_units is 'inches', scale is 2.0, and (u, v) = (1, 0), then the vector will be 0.5 inches long.

    If scale_units is 'width' or 'height', then the vector will be half the width/height of the axes.

    If scale_units is 'x' then the vector will be 0.5 x-axis units. To plot vectors in the x-y plane, with u and v having the same units as x and y, use angles='xy', scale_units='xy', scale=1.

  • width (float, optional) -- Shaft width in arrow units; default depends on choice of units, above, and number of vectors; a typical starting value is about 0.005 times the width of the plot.

  • headwidth (float, default: 3) -- Head width as multiple of shaft width.

  • headlength (float, default: 5) -- Head length as multiple of shaft width.

  • headaxislength (float, default: 4.5) -- Head length at shaft intersection.

  • minshaft (float, default: 1) -- Length below which arrow scales, in units of head length. Do not set this to less than 1, or small arrows will look terrible!

  • minlength (float, default: 1) -- Minimum length as a multiple of shaft width; if an arrow length is less than this, plot a dot (hexagon) of this diameter instead.

  • pivot ({'tail', 'mid', 'middle', 'tip'}, default: 'tail') --

    The part of the arrow that is anchored to the X, Y grid. The arrow rotates about this point.

    'mid' is a synonym for 'middle'.

  • color (color or color sequence, optional) --

    Explicit color(s) for the arrows. If C has been set, color has no effect.

    This is a synonym for the ~.PolyCollection facecolor parameter.

  • **kwargs (~matplotlib.collections.PolyCollection properties, optional) --

    All other keyword arguments are passed on to .PolyCollection:

    Properties: 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: array-like or scalar or None animated: bool antialiased or aa or antialiaseds: bool or list of bools array: ndarray or None capstyle: .CapStyle or {'butt', 'projecting', 'round'} clim: (vmin: float, vmax: float) clip_box: .Bbox clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: color or list of rgba tuples contains: unknown edgecolor or ec or edgecolors: color or list of colors or 'face' facecolor or facecolors or fc: color or list of colors figure: .Figure gid: str hatch: {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'} in_layout: bool joinstyle: .JoinStyle or {'miter', 'round', 'bevel'} label: object linestyle or dashes or linestyles or ls: str or tuple or list thereof linewidth or linewidths or lw: float or list of floats norm: .Normalize or None offset_position: unknown offsets: (N, 2) or (2,) array-like path_effects: .AbstractPathEffect picker: None or bool or float or callable pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: .Transform url: str urls: list of str or None visible: bool zorder: float

See also

Axes.quiverkey

Add a key to a quiver plot.

savefig(*args, **kwargs)[source]

Copy of plt.savefig(). Original docstring is ...

Save the current figure.

Call signature:

savefig(fname, dpi=None, facecolor='w', edgecolor='w',
        orientation='portrait', papertype=None, format=None,
        transparent=False, bbox_inches=None, pad_inches=0.1,
        frameon=None, metadata=None)

The available output formats depend on the backend being used.

Parameters
  • fname (str or path-like or binary file-like) --

    A path, or a Python file-like object, or possibly some backend-dependent object such as matplotlib.backends.backend_pdf.PdfPages.

    If format is set, it determines the output format, and the file is saved as fname. Note that fname is used verbatim, and there is no attempt to make the extension, if any, of fname match format, and no extension is appended.

    If format is not set, then the format is inferred from the extension of fname, if there is one. If format is not set and fname has no extension, then the file is saved with :rc:`savefig.format` and the appropriate extension is appended to fname.

  • dpi (float or 'figure', default: :rc:`savefig.dpi`) -- The resolution in dots per inch. If 'figure', use the figure's dpi value.

  • quality (int, default: :rc:`savefig.jpeg_quality`) --

    Applicable only if format is 'jpg' or 'jpeg', ignored otherwise.

    The image quality, on a scale from 1 (worst) to 95 (best). Values above 95 should be avoided; 100 disables portions of the JPEG compression algorithm, and results in large files with hardly any gain in image quality.

    This parameter is deprecated.

  • optimize (bool, default: False) --

    Applicable only if format is 'jpg' or 'jpeg', ignored otherwise.

    Whether the encoder should make an extra pass over the image in order to select optimal encoder settings.

    This parameter is deprecated.

  • progressive (bool, default: False) --

    Applicable only if format is 'jpg' or 'jpeg', ignored otherwise.

    Whether the image should be stored as a progressive JPEG file.

    This parameter is deprecated.

  • facecolor (color or 'auto', default: :rc:`savefig.facecolor`) -- The facecolor of the figure. If 'auto', use the current figure facecolor.

  • edgecolor (color or 'auto', default: :rc:`savefig.edgecolor`) -- The edgecolor of the figure. If 'auto', use the current figure edgecolor.

  • orientation ({'landscape', 'portrait'}) -- Currently only supported by the postscript backend.

  • papertype (str) -- One of 'letter', 'legal', 'executive', 'ledger', 'a0' through 'a10', 'b0' through 'b10'. Only supported for postscript output.

  • format (str) -- The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this is unset is documented under fname.

  • transparent (bool) -- If True, the Axes patches will all be transparent; the figure patch will also be transparent unless facecolor and/or edgecolor are specified via kwargs. This is useful, for example, for displaying a plot on top of a colored background on a web page. The transparency of these patches will be restored to their original values upon exit of this function.

  • bbox_inches (str or .Bbox, default: :rc:`savefig.bbox`) -- Bounding box in inches: only the given portion of the figure is saved. If 'tight', try to figure out the tight bbox of the figure.

  • pad_inches (float, default: :rc:`savefig.pad_inches`) -- Amount of padding around the figure when bbox_inches is 'tight'.

  • bbox_extra_artists (list of ~matplotlib.artist.Artist, optional) -- A list of extra artists that will be considered when the tight bbox is calculated.

  • backend (str, optional) -- Use a non-default backend to render the file, e.g. to render a png file with the "cairo" backend rather than the default "agg", or a pdf file with the "pgf" backend rather than the default "pdf". Note that the default backend is normally sufficient. See the-builtin-backends for a list of valid backends for each file format. Custom backends can be referenced as "module://...".

  • metadata (dict, optional) --

    Key/value pairs to store in the image metadata. The supported keys and defaults depend on the image format and backend:

    • 'png' with Agg backend: See the parameter metadata of ~.FigureCanvasAgg.print_png.

    • 'pdf' with pdf backend: See the parameter metadata of ~.backend_pdf.PdfPages.

    • 'svg' with svg backend: See the parameter metadata of ~.FigureCanvasSVG.print_svg.

    • 'eps' and 'ps' with PS backend: Only 'Creator' is supported.

  • pil_kwargs (dict, optional) -- Additional keyword arguments that are passed to PIL.Image.Image.save when saving the figure.

scatter(*args, **kwargs)[source]

Copy of plt.scatter(). Original docstring is ...

A scatter plot of y vs. x with varying marker size and/or color.

Parameters
  • x (float or array-like, shape (n, )) -- The data positions.

  • y (float or array-like, shape (n, )) -- The data positions.

  • s (float or array-like, shape (n, ), optional) -- The marker size in points**2. Default is rcParams['lines.markersize'] ** 2.

  • c (array-like or list of colors or color, optional) --

    The marker colors. Possible values:

    • A scalar or sequence of n numbers to be mapped to colors using cmap and norm.

    • A 2D array in which the rows are RGB or RGBA.

    • A sequence of colors of length n.

    • A single color format string.

    Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. If you want to specify the same RGB or RGBA value for all points, use a 2D array with a single row. Otherwise, value- matching will have precedence in case of a size matching with x and y.

    If you wish to specify a single color for all points prefer the color keyword argument.

    Defaults to None. In that case the marker color is determined by the value of color, facecolor or facecolors. In case those are not specified or None, the marker color is determined by the next color of the Axes' current "shape and fill" color cycle. This cycle defaults to :rc:`axes.prop_cycle`.

  • marker (~.markers.MarkerStyle, default: :rc:`scatter.marker`) -- The marker style. marker can be either an instance of the class or the text shorthand for a particular marker. See matplotlib.markers for more information about marker styles.

  • cmap (str or ~matplotlib.colors.Colormap, default: :rc:`image.cmap`) -- A .Colormap instance or registered colormap name. cmap is only used if c is an array of floats.

  • norm (~matplotlib.colors.Normalize, default: None) -- If c is an array of floats, norm is used to scale the color data, c, in the range 0 to 1, in order to map into the colormap cmap. If None, use the default .colors.Normalize.

  • vmin (float, default: None) -- vmin and vmax are used in conjunction with the default norm to map the color array c to the colormap cmap. If None, the respective min and max of the color array is used. It is deprecated to use vmin/vmax when norm is given.

  • vmax (float, default: None) -- vmin and vmax are used in conjunction with the default norm to map the color array c to the colormap cmap. If None, the respective min and max of the color array is used. It is deprecated to use vmin/vmax when norm is given.

  • alpha (float, default: None) -- The alpha blending value, between 0 (transparent) and 1 (opaque).

  • linewidths (float or array-like, default: :rc:`lines.linewidth`) -- The linewidth of the marker edges. Note: The default edgecolors is 'face'. You may want to change this as well.

  • edgecolors ({'face', 'none', None} or color or sequence of color, default: :rc:`scatter.edgecolors`) --

    The edge color of the marker. Possible values:

    • 'face': The edge color will always be the same as the face color.

    • 'none': No patch boundary will be drawn.

    • A color or sequence of colors.

    For non-filled markers, edgecolors is ignored. Instead, the color is determined like with 'face', i.e. from c, colors, or facecolors.

  • plotnonfinite (bool, default: False) -- Whether to plot points with nonfinite c (i.e. inf, -inf or nan). If True the points are drawn with the bad colormap color (see .Colormap.set_bad).

  • **kwargs (~matplotlib.collections.Collection properties) --

Returns

Return type

~matplotlib.collections.PathCollection

See also

plot

To plot scatter plots when markers are identical in size and color.

Notes

  • The .plot function will be faster for scatterplots where markers don't vary in size or color.

  • Any or all of x, y, s, and c may be masked arrays, in which case all masks will be combined and only unmasked points will be plotted.

  • Fundamentally, scatter works with 1D arrays; x, y, s, and c may be input as N-D arrays, but within scatter they will be flattened. The exception is c, which will be flattened only if its size matches the size of x and y.

Note

In addition to the above described arguments, this function can take a data keyword argument. If such a data argument is given, the following arguments can also be string s, which is interpreted as data[s] (unless this raises an exception): x, y, s, linewidths, edgecolors, c, facecolor, facecolors, color.

Objects passed as data must support item access (data[s]) and membership test (s in data).

subplots(*args, **kwargs)[source]

Copy of plt.subplots(). Original docstring is ...

Create a figure and a set of subplots.

This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call.

Parameters
  • nrows (int, default: 1) -- Number of rows/columns of the subplot grid.

  • ncols (int, default: 1) -- Number of rows/columns of the subplot grid.

  • sharex (bool or {'none', 'all', 'row', 'col'}, default: False) --

    Controls sharing of properties among x (sharex) or y (sharey) axes:

    • 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 ~matplotlib.axes.Axes.tick_params.

    When subplots have a shared axis that has units, calling ~matplotlib.axis.Axis.set_units will update each axis with the new units.

  • sharey (bool or {'none', 'all', 'row', 'col'}, default: False) --

    Controls sharing of properties among x (sharex) or y (sharey) axes:

    • 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 ~matplotlib.axes.Axes.tick_params.

    When subplots have a shared axis that has units, calling ~matplotlib.axis.Axis.set_units will update each axis with the new units.

  • squeeze (bool, default: True) --

    • If True, extra dimensions are squeezed out from the returned array of ~matplotlib.axes.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_kw (dict, optional) -- Dict with keywords passed to the ~matplotlib.figure.Figure.add_subplot call used to create each subplot.

  • gridspec_kw (dict, optional) -- Dict with keywords passed to the ~matplotlib.gridspec.GridSpec constructor used to create the grid the subplots are placed on.

  • **fig_kw -- All additional keyword arguments are passed to the .pyplot.figure call.

Returns

  • fig (~.figure.Figure)

  • ax (.axes.Axes or array of Axes) -- ax can be either a single ~matplotlib.axes.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.

    Typical idioms for handling the return value are:

    # using the variable ax for single a Axes
    fig, ax = plt.subplots()
    
    # using the variable axs for multiple Axes
    fig, axs = plt.subplots(2, 2)
    
    # using tuple unpacking for multiple Axes
    fig, (ax1, ax2) = plt.subplots(1, 2)
    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
    

    The names ax and pluralized axs are preferred over axes because for the latter it's not clear if it refers to a single ~.axes.Axes instance or a collection of these.

See also

pyplot.figure, pyplot.subplot, pyplot.axes, Figure.subplots, Figure.add_subplot

Examples

# First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

# Create just a figure and only one subplot
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')

# Create two subplots and unpack the output array immediately
f, (ax1, ax2) = plt.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
fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar"))
axs[0, 0].plot(x, y)
axs[1, 1].scatter(x, y)

# Share a X axis with each column of subplots
plt.subplots(2, 2, sharex='col')

# Share a Y axis with each row of subplots
plt.subplots(2, 2, sharey='row')

# Share both X and Y axes with all subplots
plt.subplots(2, 2, sharex='all', sharey='all')

# Note that this is the same as
plt.subplots(2, 2, sharex=True, sharey=True)

# Create figure number 10 with a single subplot
# and clears it if it already exists.
fig, ax = plt.subplots(num=10, clear=True)
text(*args, **kwargs)[source]

Copy of plt.text(). Original docstring is ...

Add text to the Axes.

Add the text s to the Axes at location x, y in data coordinates.

Parameters
  • x (float) -- The position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the transform parameter.

  • y (float) -- The position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the transform parameter.

  • s (str) -- The text.

  • fontdict (dict, default: None) -- A dictionary to override the default text properties. If fontdict is None, the defaults are determined by .rcParams.

  • **kwargs (~matplotlib.text.Text properties.) --

    Other miscellaneous text parameters.

    Properties: 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: .Bbox clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color contains: unknown 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'} 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

Returns

The created .Text instance.

Return type

.Text

Examples

Individual keyword arguments can be used to override any given parameter:

>>> text(x, y, s, fontsize=12)

The default transform specifies that text is in data coords, alternatively, you can specify text in axis coords ((0, 0) is lower-left and (1, 1) is upper-right). The example below places text in the center of the Axes:

>>> text(0.5, 0.5, 'matplotlib', horizontalalignment='center',
...      verticalalignment='center', transform=ax.transAxes)

You can put a rectangular box around the text instance (e.g., to set a background color) by using the keyword bbox. bbox is a dictionary of ~matplotlib.patches.Rectangle properties. For example:

>>> text(x, y, s, bbox=dict(facecolor='red', alpha=0.5))
title(*args, **kwargs)[source]

Copy of plt.title(). Original docstring is ...

Set a title for the Axes.

Set one of the three available Axes titles. The available titles are positioned above the Axes in the center, flush with the left edge, and flush with the right edge.

Parameters
  • label (str) -- Text to use for the title

  • fontdict (dict) --

    A dictionary controlling the appearance of the title text, the default fontdict is:

    {'fontsize': rcParams['axes.titlesize'],
     'fontweight': rcParams['axes.titleweight'],
     'color': rcParams['axes.titlecolor'],
     'verticalalignment': 'baseline',
     'horizontalalignment': loc}
    

  • loc ({'center', 'left', 'right'}, default: :rc:`axes.titlelocation`) -- Which title to set.

  • y (float, default: :rc:`axes.titley`) -- Vertical Axes loation for the title (1.0 is the top). If None (the default), y is determined automatically to avoid decorators on the Axes.

  • pad (float, default: :rc:`axes.titlepad`) -- The offset of the title from the top of the Axes, in points.

  • **kwargs (.Text properties) -- Other keyword arguments are text properties, see .Text for a list of valid text properties.

Returns

The matplotlib text instance representing the title

Return type

.Text

twinx()[source]

Copy of plt.twinx(). Original docstring is ...

Make and return a second axes that shares the x-axis. The new axes will overlay ax (or the current axes if ax is None), and its ticks will be on the right.

Examples

/gallery/subplots_axes_and_figures/two_scales

twiny()[source]

Copy of plt.twiny(). Original docstring is ...

Make and return a second axes that shares the y-axis. The new axes will overlay ax (or the current axes if ax is None), and its ticks will be on the top.

Examples

/gallery/subplots_axes_and_figures/two_scales

xlabel(*args, **kwargs)[source]

Copy of plt.xlabel(). Original docstring is ...

Set the label for the x-axis.

Parameters
  • xlabel (str) -- The label text.

  • labelpad (float, default: :rc:`axes.labelpad`) -- Spacing in points from the axes bounding box including ticks and tick labels. If None, the previous value is left as is.

  • loc ({'left', 'center', 'right'}, default: :rc:`xaxis.labellocation`) -- The label position. This is a high-level alternative for passing parameters x and horizontalalignment.

  • **kwargs (.Text properties) -- .Text properties control the appearance of the label.

See also

text

Documents the properties supported by .Text.

xlim(*args, **kwargs)[source]

Copy of plt.xlim(). Original docstring is ...

Get or set the x limits of the current axes.

Call signatures:

left, right = xlim()  # return the current xlim
xlim((left, right))   # set the xlim to left, right
xlim(left, right)     # set the xlim to left, right

If you do not specify args, you can pass left or right as kwargs, i.e.:

xlim(right=3)  # adjust the right leaving left unchanged
xlim(left=1)  # adjust the left leaving right unchanged

Setting limits turns autoscaling off for the x-axis.

Returns

A tuple of the new x-axis limits.

Return type

left, right

Notes

Calling this function with no arguments (e.g. xlim()) is the pyplot equivalent of calling ~.Axes.get_xlim on the current axes. Calling this function with arguments is the pyplot equivalent of calling ~.Axes.set_xlim on the current axes. All arguments are passed though.

xscale(scale=None)[source]

Copy of plt.xscale(). Original docstring is ...

Set the x-axis scale.

Parameters
  • value ({"linear", "log", "symlog", "logit", ...} or .ScaleBase) -- The axis scale type to apply.

  • **kwargs --

    Different keyword arguments are accepted, depending on the scale. See the respective class keyword arguments:

    • matplotlib.scale.LinearScale

    • matplotlib.scale.LogScale

    • matplotlib.scale.SymmetricalLogScale

    • matplotlib.scale.LogitScale

    • matplotlib.scale.FuncScale

Notes

By default, Matplotlib supports the above mentioned scales. Additionally, custom scales may be registered using matplotlib.scale.register_scale. These scales can then also be used here.

xticks(ticks=None, labels=None, **kwargs)[source]

Copy of plt.xticks(). Original docstring is ...

Get or set the current tick locations and labels of the x-axis.

Pass no arguments to return the current values without modifying them.

Parameters
  • ticks (array-like, optional) -- The list of xtick locations. Passing an empty list removes all xticks.

  • labels (array-like, optional) -- The labels to place at the given ticks locations. This argument can only be passed if ticks is passed as well.

  • **kwargs -- .Text properties can be used to control the appearance of the labels.

Returns

  • locs -- The list of xtick locations.

  • labels -- The list of xlabel .Text objects.

Notes

Calling this function with no arguments (e.g. xticks()) is the pyplot equivalent of calling ~.Axes.get_xticks and ~.Axes.get_xticklabels on the current axes. Calling this function with arguments is the pyplot equivalent of calling ~.Axes.set_xticks and ~.Axes.set_xticklabels on the current axes.

Examples

>>> locs, labels = xticks()  # Get the current locations and labels.
>>> xticks(np.arange(0, 1, step=0.2))  # Set label locations.
>>> xticks(np.arange(3), ['Tom', 'Dick', 'Sue'])  # Set text labels.
>>> xticks([0, 1, 2], ['January', 'February', 'March'],
...        rotation=20)  # Set text labels and properties.
>>> xticks([])  # Disable xticks.
ylabel(*args, **kwargs)[source]

Copy of plt.ylabel(). Original docstring is ...

Set the label for the y-axis.

Parameters
  • ylabel (str) -- The label text.

  • labelpad (float, default: :rc:`axes.labelpad`) -- Spacing in points from the axes bounding box including ticks and tick labels. If None, the previous value is left as is.

  • loc ({'bottom', 'center', 'top'}, default: :rc:`yaxis.labellocation`) -- The label position. This is a high-level alternative for passing parameters y and horizontalalignment.

  • **kwargs (.Text properties) -- .Text properties control the appearance of the label.

See also

text

Documents the properties supported by .Text.

ylim(*args, **kwargs)[source]

Copy of plt.ylim(). Original docstring is ...

Get or set the y-limits of the current axes.

Call signatures:

bottom, top = ylim()  # return the current ylim
ylim((bottom, top))   # set the ylim to bottom, top
ylim(bottom, top)     # set the ylim to bottom, top

If you do not specify args, you can alternatively pass bottom or top as kwargs, i.e.:

ylim(top=3)  # adjust the top leaving bottom unchanged
ylim(bottom=1)  # adjust the bottom leaving top unchanged

Setting limits turns autoscaling off for the y-axis.

Returns

A tuple of the new y-axis limits.

Return type

bottom, top

Notes

Calling this function with no arguments (e.g. ylim()) is the pyplot equivalent of calling ~.Axes.get_ylim on the current axes. Calling this function with arguments is the pyplot equivalent of calling ~.Axes.set_ylim on the current axes. All arguments are passed though.

yscale(scale=None)[source]

Copy of plt.yscale(). Original docstring is ...

Set the y-axis scale.

Parameters
  • value ({"linear", "log", "symlog", "logit", ...} or .ScaleBase) -- The axis scale type to apply.

  • **kwargs --

    Different keyword arguments are accepted, depending on the scale. See the respective class keyword arguments:

    • matplotlib.scale.LinearScale

    • matplotlib.scale.LogScale

    • matplotlib.scale.SymmetricalLogScale

    • matplotlib.scale.LogitScale

    • matplotlib.scale.FuncScale

Notes

By default, Matplotlib supports the above mentioned scales. Additionally, custom scales may be registered using matplotlib.scale.register_scale. These scales can then also be used here.

yticks(ticks=None, labels=None, **kwargs)[source]

Copy of plt.yticks(). Original docstring is ...

Get or set the current tick locations and labels of the y-axis.

Pass no arguments to return the current values without modifying them.

Parameters
  • ticks (array-like, optional) -- The list of ytick locations. Passing an empty list removes all yticks.

  • labels (array-like, optional) -- The labels to place at the given ticks locations. This argument can only be passed if ticks is passed as well.

  • **kwargs -- .Text properties can be used to control the appearance of the labels.

Returns

  • locs -- The list of ytick locations.

  • labels -- The list of ylabel .Text objects.

Notes

Calling this function with no arguments (e.g. yticks()) is the pyplot equivalent of calling ~.Axes.get_yticks and ~.Axes.get_yticklabels on the current axes. Calling this function with arguments is the pyplot equivalent of calling ~.Axes.set_yticks and ~.Axes.set_yticklabels on the current axes.

Examples

>>> locs, labels = yticks()  # Get the current locations and labels.
>>> yticks(np.arange(0, 1, step=0.2))  # Set label locations.
>>> yticks(np.arange(3), ['Tom', 'Dick', 'Sue'])  # Set text labels.
>>> yticks([0, 1, 2], ['January', 'February', 'March'],
...        rotation=45)  # Set text labels and properties.
>>> yticks([])  # Disable yticks.
class magicclass.widgets.FloatRangeSlider(value=UNSET, min=0, max=1000, orientation: str = 'horizontal', nullable: bool = True, **kwargs)[source]

Bases: magicclass.widgets.misc.AbstractRangeSlider[float]

name: str
class magicclass.widgets.FrameContainer(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, layout: str = 'vertical', widgets: Sequence[Widget] = (), labels=True)

Bases: magicgui.widgets._bases.widget.Widget, magicgui.widgets._bases.mixins._OrientationMixin, MutableSequence[magicgui.widgets._bases.widget.Widget]

A QGroupBox like container without title.

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

class magicclass.widgets.FreeWidget(layout='vertical', **kwargs)[source]

Bases: magicgui.widgets._bases.widget.Widget

A Widget class with any QWidget as a child.

set_contextmenu(contextmenugui: ContextMenuGui)[source]
set_widget(widget: PyQt5.QtWidgets.QWidget, *args)[source]

Set the central widget to the widget.

class magicclass.widgets.GroupBoxContainer(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, layout: str = 'vertical', widgets: Sequence[Widget] = (), labels=True)

Bases: magicgui.widgets._bases.widget.Widget, magicgui.widgets._bases.mixins._OrientationMixin, MutableSequence[magicgui.widgets._bases.widget.Widget]

A QGroupBox like container

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

property name
class magicclass.widgets.HCollapsibleContainer(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, layout: str = 'vertical', widgets: Sequence[Widget] = (), labels=True)

Bases: magicgui.widgets._bases.widget.Widget, magicgui.widgets._bases.mixins._OrientationMixin, MutableSequence[magicgui.widgets._bases.widget.Widget]

A collapsible Container Widget.

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

property collapsed: bool
class magicclass.widgets.ListContainer(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, layout: str = 'vertical', widgets: Sequence[Widget] = (), labels=True)

Bases: magicgui.widgets._bases.widget.Widget, magicgui.widgets._bases.mixins._OrientationMixin, MutableSequence[magicgui.widgets._bases.widget.Widget]

A Container Widget that support drag and drop.

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

property current_index
class magicclass.widgets.ListEdit(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, layout: str = 'horizontal', widgets: Sequence[Widget] = (), labels: bool = False, value: Iterable[_V] | _Unset = UNSET, nullable: bool = False, options: WidgetOptions = None)

Bases: magicgui.widgets._bases.widget.Widget, magicgui.widgets._bases.mixins._OrientationMixin, MutableSequence[magicgui.widgets._bases.widget.Widget]

A widget to represent a list of values.

A ListEdit container can create a list with multiple objects of same type. It will contain many child widgets and their value is represented as a Python list object. If a list is given as the initial value, types of child widgets are determined from the contents. Number of contents can be adjusted with +/- buttons.

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

  • name -- The name of the parameter represented by this widget. by default ""

  • annotation -- The type annotation for the parameter represented by the widget, by default None

  • label -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip -- A tooltip to display when hovering over the widget.

  • visible -- Whether the widget is visible, by default True.

  • backend_kwargs -- keyword argument to pass to the backend widget constructor.

  • options (WidgetOptions) -- Widget options of child widgets.

property annotation

Return type annotation for the parameter represented by the widget. ForwardRefs will be resolve when setting the annotation. For ListEdit, annotation will be like 'list[str]'.

property buttons_visible: bool

Toggle visibility of +/- buttons.

property data: magicclass.widgets.sequence.ListDataView

Return a data view of current value.

property value: list

Return current value as a list object.

class magicclass.widgets.ListWidget(value: Optional[Iterable[Any]] = None, dragdrop: bool = True, **kwargs)[source]

Bases: magicclass.widgets.pywidgets.object.BaseWidget, MutableSequence

clear()[source]

Clear all the items.

index(obj: Any, start: int = 0, stop: Optional[int] = None) int[source]

Find object or list widget item from the list widget.

Parameters
  • obj (Any) -- Object to find. If a PyListWidgetItem is given, the index of the item (not the tagged object) is searched for.

  • start (int, optional) -- Starting index, by default 0

  • stop (int, optional) -- Index to stop searching.

Returns

Index of object.

Return type

int

Raises

ValueError -- If object was not found.

insert(i: int, obj: Any)[source]

Insert object of any type to the list.

property value: list[typing.Any]

Get all the contents as a Python list.

Returns

Contents of the list widget.

Return type

list

class magicclass.widgets.Logger[source]

Bases: magicgui.widgets._bases.widget.Widget, logging.Handler

A widget for logging.

Examples

Create widget as other magicgui or magicclass widgets.

logger = Logger(name="my logger")  # magicgui way

# magicclass way
@magicclass
class Main:
    logger = field(Logger, name="my logger")

# This is OK
@magicclass
class Main:
    logger = Logger()

Print something in the widget

# print something in the widget.
logger.print("text")

# a context manager that change the destination of print function.
with logger.set_stdout():
    print("text")
    function_that_print_something()

# permanently change the destination of print function
sys.stdout = logger

Logging in the widget

with logger.set_logger():
    function_that_log_something()

logging.getLogger(__name__).addHandler(logger)

Inline plot in the widget

with logger.set_plt():
    plt.plot(np.random.random(100))
clear()[source]

Clear all the histories.

close() None[source]

Close widget.

current_logger: Logger | None = None
emit(record)[source]

Do whatever it takes to actually log the specified logging record.

This version is intended to be implemented by subclasses and so raises a NotImplementedError.

flush()[source]

Ensure all logging output has been flushed.

This version does nothing and is intended to be implemented by subclasses.

print(*msg, sep=' ', end='\n')[source]

Print things in the end of the logger widget.

print_figure(fig: Figure) None[source]

Print matplotlib Figure object like inline plot.

print_html(html: str, end='<br></br>')[source]

Print things in the end of the logger widget using HTML string.

print_image(arr: str | Path | np.ndarray | Image, vmin=None, vmax=None, cmap=None, norm=None, width=None, height=None) None[source]

Print an array as an image in the logger widget. Can be a path.

print_rst(rst: str, end='\n')[source]

Print things in the end of the logger widget using rST string.

print_table(table, header: bool = True, index: bool = True, precision: int | None = None)[source]

Print object as a table in the logger widget.

Parameters
  • table (table-like object) -- Any object that can be passed to pandas.DataFrame can be used.

  • header (bool, default is True) -- Whether to show the header row.

  • index (bool, default is True) -- Whether to show the index column.

  • precision (int, options) -- If given, float value will be rounded by this parameter.

set_logger(name=None)[source]

A context manager for logging things in this widget.

set_plt(style: str | None) None[source]
set_plt(rc_context: dict[str, Any]) None

A context manager for inline plot in the logger widget.

set_stdout()[source]

A context manager for printing things in this widget.

write(msg) None[source]
class magicclass.widgets.OptionalWidget(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, layout='vertical', widgets: Sequence[Widget] = (), labels=True, inner_widget: type[ValueWidget] | None = None, text: str = None, nullable=True, value=UNSET, options=None)

Bases: magicgui.widgets._bases.widget.Widget, magicgui.widgets._bases.mixins._OrientationMixin, MutableSequence[magicgui.widgets._bases.widget.Widget]

A container that can represent optional argument.

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

  • name -- The name of the parameter represented by this widget. by default ""

  • annotation -- The type annotation for the parameter represented by the widget, by default None

  • label -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip -- A tooltip to display when hovering over the widget.

  • visible -- Whether the widget is visible, by default True.

  • backend_kwargs -- keyword argument to pass to the backend widget constructor.

  • text (str) -- Text of checkbox.

  • value (Any) -- Initial value.

  • options (dict) -- Widget options of the inner value widget.

property text: str
property value: Any
class magicclass.widgets.RangeSlider(value=UNSET, min=0, max=1000, orientation: str = 'horizontal', nullable: bool = True, **kwargs)[source]

Bases: magicclass.widgets.misc.AbstractRangeSlider[int]

name: str
class magicclass.widgets.ScrollableContainer(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, layout: str = 'vertical', widgets: Sequence[Widget] = (), labels=True)

Bases: magicgui.widgets._bases.widget.Widget, magicgui.widgets._bases.mixins._OrientationMixin, MutableSequence[magicgui.widgets._bases.widget.Widget]

A scrollable Container Widget.

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

class magicclass.widgets.Separator(orientation: str = 'horizontal', text: str = '', name: str = '', button: bool = False)[source]

Bases: magicclass.widgets.utils.FreeWidget

A Separator widget that can be used in both widgets and menus. This widget is not actually added to menus or toolbars.

btn_clicked

Signal descriptor, for declaring a signal on a class.

This is designed to be used as a class attribute, with the supported signature(s) provided in the contructor:

class MyEmitter:

changed = Signal(int) # changed will emit an int

def receiver(arg: int):

print("new value:", arg)

emitter = MyEmitter() emitter.changed.connect(receiver) emitter.emit(1)

Note: in the example above, MyEmitter.changed is an instance of Signal, and emitter.changed is an instance of SignalInstance.

Parameters
  • *types (sequence of Type) -- A sequence of individual types

  • description (str, optional) -- Optional descriptive text for the signal. (not used internally).

  • name (str, optional) -- Optional name of the signal. If it is not specified then the name of the class attribute that is bound to the signal will be used. default None

  • check_nargs_on_connect (str, optional) -- Whether to check the number of positional args against signature when connecting a new callback. This can also be provided at connection time using .connect(..., check_nargs=True). By default, True.

  • check_types_on_connect (str, optional) -- Whether to check the callback parameter types against signature when connecting a new callback. This can also be provided at connection time using .connect(..., check_types=True). By default, False.

property btn_text
central_widget: QWidget
name: str
class magicclass.widgets.SplitterContainer(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, layout: str = 'vertical', widgets: Sequence[Widget] = (), labels=True)

Bases: magicgui.widgets._bases.widget.Widget, magicgui.widgets._bases.mixins._OrientationMixin, MutableSequence[magicgui.widgets._bases.widget.Widget]

A Container equipped with splitter

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

class magicclass.widgets.SpreadSheet[source]

Bases: magicclass.widgets.utils.FreeWidget, MutableSequence[magicgui.widgets._table.Table]

A simple spread sheet widget.

index(value[, start[, stop]]) integer -- return first index of value.[source]

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

insert(key: int, value)[source]

S.insert(index, value) -- insert value before index

rename(index: int, name: str)[source]
class magicclass.widgets.StackedContainer(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, layout: str = 'vertical', widgets: Sequence[Widget] = (), labels=True)

Bases: magicgui.widgets._bases.widget.Widget, magicgui.widgets._bases.mixins._OrientationMixin, MutableSequence[magicgui.widgets._bases.widget.Widget]

A stacked Container Widget

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

property current_index
class magicclass.widgets.SubWindowsContainer(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, layout: str = 'vertical', widgets: Sequence[Widget] = (), labels=True)

Bases: magicgui.widgets._bases.widget.Widget, magicgui.widgets._bases.mixins._OrientationMixin, MutableSequence[magicgui.widgets._bases.widget.Widget]

A window-in-window container

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

class magicclass.widgets.TabbedContainer(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, layout: str = 'vertical', widgets: Sequence[Widget] = (), labels=True)

Bases: magicgui.widgets._bases.widget.Widget, magicgui.widgets._bases.mixins._OrientationMixin, MutableSequence[magicgui.widgets._bases.widget.Widget]

A tab categorized Container Widget.

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

property current_index
class magicclass.widgets.ToolBoxContainer(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, layout: str = 'vertical', widgets: Sequence[Widget] = (), labels=True)

Bases: magicgui.widgets._bases.widget.Widget, magicgui.widgets._bases.mixins._OrientationMixin, MutableSequence[magicgui.widgets._bases.widget.Widget]

A Tool box Widget.

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

property current_index
class magicclass.widgets.TupleEdit(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, layout: str = 'horizontal', widgets: Sequence[Widget] = (), labels=True, value: Iterable[_V] | _Unset = UNSET, nullable: bool = False, options: WidgetOptions = None)

Bases: magicgui.widgets._bases.widget.Widget, magicgui.widgets._bases.mixins._OrientationMixin, MutableSequence[magicgui.widgets._bases.widget.Widget]

A widget to represent a tuple of values.

A TupleEdit container has several child widgets of different type. Their value is represented as a Python tuple object. If a tuple is given as the initial value, types of child widgets are determined one by one. Unlike ListEdit, number of contents is not editable.

Parameters
  • name (str) -- The name of the parameter represented by this widget. by default ""

  • annotation (Any) -- The type annotation for the parameter represented by the widget, by default None

  • label (str) -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip (str) -- A tooltip to display when hovering over the widget.

  • visible (bool) -- Whether the widget is visible, by default True.

  • backend_kwargs (dict) -- keyword argument to pass to the backend widget constructor.

  • name -- The name of the parameter represented by this widget. by default ""

  • annotation -- The type annotation for the parameter represented by the widget, by default None

  • label -- A string to use for an associated Label widget (if this widget is being shown in a Container widget, and labels are on). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI.

  • tooltip -- A tooltip to display when hovering over the widget.

  • visible -- Whether the widget is visible, by default True.

  • backend_kwargs -- keyword argument to pass to the backend widget constructor.

  • options (WidgetOptions) -- Widget options of child widgets.

property annotation

Return type annotation for the parameter represented by the widget. ForwardRefs will be resolve when setting the annotation. For TupleEdit, annotation will be like 'tuple[str, int]'.

property value: tuple

Return current value as a tuple.