scitex.plt API Reference
Note
scitex.plt wraps matplotlib with data-tracking axes. The plotting API
is migrating to figrecipe.
See PLT Module (stx.plt) for usage documentation.
Drop-in replacement for matplotlib.pyplot with recording capabilities.
This module provides a convenient way to use figrecipe as a direct replacement for matplotlib.pyplot. Simply change your import statement:
# Before (standard matplotlib) import matplotlib.pyplot as plt
# After (figrecipe with recording) import figrecipe.pyplot as plt
All your existing code will work unchanged, but figures created with plt.subplots() will automatically have recording capabilities.
Examples
>>> import figrecipe.pyplot as plt
>>> import numpy as np
>>>
>>> x = np.linspace(0, 10, 100)
>>> y = np.sin(x)
>>>
>>> fig, ax = plt.subplots() # Recording-enabled
>>> ax.plot(x, y, color='red', id='sine_wave')
>>> fig.save_recipe('my_figure.yaml') # Save as recipe
>>>
>>> # All other pyplot functions work as usual
>>> plt.show()
>>> plt.savefig('output.png')
- scitex.plt.subplots(nrows=1, ncols=1, axes_width_mm=None, axes_height_mm=None, margin_left_mm=None, margin_right_mm=None, margin_bottom_mm=None, margin_top_mm=None, space_w_mm=None, space_h_mm=None, style=None, apply_style_mm=True, panel_labels=None, **kwargs)[source]
Create a figure with recording-enabled axes.
This is a drop-in replacement for plt.subplots() that wraps the returned figure and axes with recording capabilities.
Supports mm-based layout control for publication-quality figures.
- Parameters:
nrows (int) – Number of rows and columns of subplots.
ncols (int) – Number of rows and columns of subplots.
axes_width_mm (float, optional) – Axes dimensions in mm.
axes_height_mm (float, optional) – Axes dimensions in mm.
margin_left_mm (float, optional) – Left/right margins in mm.
margin_right_mm (float, optional) – Left/right margins in mm.
margin_bottom_mm (float, optional) – Bottom/top margins in mm.
margin_top_mm (float, optional) – Bottom/top margins in mm.
space_w_mm (float, optional) – Horizontal/vertical spacing between axes in mm.
space_h_mm (float, optional) – Horizontal/vertical spacing between axes in mm.
style (dict, optional) – Style configuration dictionary.
apply_style_mm (bool) – If True (default), apply loaded style to axes.
panel_labels (bool or None) – If True, add panel labels (A, B, C, …).
**kwargs – Additional arguments passed to plt.subplots().
- Return type:
Tuple[RecordingFigure,Union[RecordingAxes,ndarray[tuple[Any,...],dtype[TypeVar(_ScalarT, bound=generic)]]]]- Returns:
fig (RecordingFigure) – Wrapped figure object.
axes (RecordingAxes or ndarray) – Wrapped axes.
- scitex.plt.figure(*args, **kwargs)[source]
Create a new figure with optional recording support.
This is a pass-through to matplotlib.pyplot.figure(). For recording support, use subplots() instead.
- Parameters:
*args – Arguments passed to matplotlib.pyplot.figure().
**kwargs – Arguments passed to matplotlib.pyplot.figure().
- Returns:
The created figure.
- Return type:
- scitex.plt.save(fig, path, **kwargs)[source]
Save a figure (recipe for RecordingFigure, or standard save).
- Parameters:
fig (RecordingFigure or Figure) – Figure to save. If RecordingFigure, saves as recipe. Otherwise, saves as image using savefig().
path (str or Path) – Output path. Use .yaml for recipe format.
**kwargs – Additional arguments for save.
- Returns:
Saved path (and ValidationResult if validate=True).
- Return type:
Path or tuple
- scitex.plt.show(*, block=None)[source]
Display all open figures.
- Parameters:
block (bool, optional) –
Whether to wait for all figures to be closed before returning.
If True block and run the GUI main loop until all figure windows are closed.
If False ensure that all figure windows are displayed and return immediately. In this case, you are responsible for ensuring that the event loop is running to have responsive figures.
Defaults to True in non-interactive mode and to False in interactive mode (see .pyplot.isinteractive).
- Return type:
See also
ionEnable interactive mode, which shows / updates the figure after every plotting command, so that calling
show()is not necessary.ioffDisable interactive mode.
savefigSave the figure to an image file instead of showing it on screen.
Notes
Saving figures to file and showing a window at the same time
If you want an image file as well as a user interface window, use .pyplot.savefig before .pyplot.show. At the end of (a blocking)
show()the figure is closed and thus unregistered from pyplot. Calling .pyplot.savefig afterwards would save a new and thus empty figure. This limitation of command order does not apply if the show is non-blocking or if you keep a reference to the figure and use .Figure.savefig.Auto-show in jupyter notebooks
The jupyter backends (activated via
%matplotlib inline,%matplotlib notebook, or%matplotlib widget), callshow()at the end of every cell by default. Thus, you usually don’t have to call it explicitly there.
- scitex.plt.savefig(*args, **kwargs)[source]
Save the current figure as an image or vector graphic to a file.
Call signature:
savefig(fname, *, transparent=None, dpi='figure', format=None, metadata=None, bbox_inches=None, pad_inches=0.1, facecolor='auto', edgecolor='auto', backend=None, **kwargs )
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
rcParams[“savefig.format”](default:'png') and the appropriate extension is appended to fname.transparent (bool, default:
rcParams[“savefig.transparent”](default:False)) –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.
If False has no effect and the color of the Axes and Figure patches are unchanged (unless the Figure patch is specified via the facecolor and/or edgecolor keyword arguments in which case those colors are used).
The transparency of these patches will be restored to their original values upon exit of this function.
This is useful, for example, for displaying a plot on top of a colored background on a web page.
dpi (float or ‘figure’, default:
rcParams[“savefig.dpi”](default:'figure')) – The resolution in dots per inch. If ‘figure’, use the figure’s dpi value.format (str) – The file format, e.g. ‘png’, ‘pdf’, ‘svg’, … The behavior when this is unset is documented under fname.
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
metadataof ~.FigureCanvasAgg.print_png.’pdf’ with pdf backend: See the parameter
metadataof ~.backend_pdf.PdfPages.’svg’ with svg backend: See the parameter
metadataof ~.FigureCanvasSVG.print_svg.’eps’ and ‘ps’ with PS backend: Only ‘Creator’ is supported.
Not supported for ‘pgf’, ‘raw’, and ‘rgba’ as those formats do not support embedding metadata. Does not currently support ‘jpg’, ‘tiff’, or ‘webp’, but may include embedding EXIF metadata in the future.
bbox_inches (str or .Bbox, default:
rcParams[“savefig.bbox”](default:None)) – 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 or ‘layout’, default:
rcParams[“savefig.pad_inches”](default:0.1)) – Amount of padding in inches around the figure when bbox_inches is ‘tight’. If ‘layout’ use the padding from the constrained or compressed layout engine; ignored if one of those engines is not in use.facecolor (color or ‘auto’, default:
rcParams[“savefig.facecolor”](default:'auto')) – The facecolor of the figure. If ‘auto’, use the current figure facecolor.edgecolor (color or ‘auto’, default:
rcParams[“savefig.edgecolor”](default:'auto')) – The edgecolor of the figure. If ‘auto’, use the current figure edgecolor.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://…”.
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.
bbox_extra_artists (list of ~matplotlib.artist.Artist, optional) – A list of extra artists that will be considered when the tight bbox is calculated.
pil_kwargs (dict, optional) – Additional keyword arguments that are passed to PIL.Image.Image.save when saving the figure.
- Return type:
Notes
Note
This is the pyplot wrapper for .Figure.savefig.
- scitex.plt.gcf()[source]
Get the current figure.
If there is currently no figure on the pyplot figure stack, a new one is created using ~.pyplot.figure(). (To test whether there is currently a figure on the pyplot figure stack, check whether ~.pyplot.get_fignums() is empty.)
- Return type:
- scitex.plt.gca()[source]
Get the current Axes.
If there is currently no Axes on this Figure, a new one is created using .Figure.add_subplot. (To test whether there is currently an Axes on a Figure, check whether
figure.axesis empty. To test whether there is currently a Figure on the pyplot figure stack, check whether .pyplot.get_fignums() is empty.)Notes
Note
This is the pyplot wrapper for .Figure.gca.
- Return type:
- scitex.plt.subplot(*args, **kwargs)[source]
Add an Axes to the current figure or retrieve an existing Axes.
This is a wrapper of .Figure.add_subplot which provides additional behavior when working with the implicit API (see the notes section).
Call signatures:
subplot(nrows, ncols, index, **kwargs) subplot(pos, **kwargs) subplot(**kwargs) subplot(ax)
- Parameters:
*args (int, (int, int, index), or .SubplotSpec, default: (1, 1, 1)) –
The position of the subplot described by one of
Three integers (nrows, ncols, index). The subplot will take the index position on a grid with nrows rows and ncols columns. index starts at 1 in the upper left corner and increases to the right. index can also be a two-tuple specifying the (first, last) indices (1-based, and including last) of the subplot, e.g.,
fig.add_subplot(3, 1, (1, 2))makes a subplot that spans the upper 2/3 of the figure.A 3-digit integer. The digits are interpreted as if given separately as three single-digit integers, i.e.
fig.add_subplot(235)is the same asfig.add_subplot(2, 3, 5). Note that this can only be used if there are no more than 9 subplots.A .SubplotSpec.
projection ({None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional) – The projection type of the subplot (~.axes.Axes). str is the name of a custom projection, see ~matplotlib.projections. The default None results in a ‘rectilinear’ projection.
polar (bool, default: False) – If True, equivalent to projection=’polar’.
sharex (~matplotlib.axes.Axes, optional) – Share the x or y ~matplotlib.axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared Axes.
sharey (~matplotlib.axes.Axes, optional) – Share the x or y ~matplotlib.axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared Axes.
label (str) – A label for the returned Axes.
**kwargs –
This method also takes the keyword arguments for the returned Axes base class; except for the figure argument. The keyword arguments for the rectilinear base class ~.axes.Axes can be found in the following table but there might also be other keyword arguments if another projection is used.
Properties: adjustable: {‘box’, ‘datalim’} agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None anchor: (float, float) or {‘C’, ‘SW’, ‘S’, ‘SE’, ‘E’, ‘NE’, …} animated: bool aspect: {‘auto’, ‘equal’} or float autoscale_on: bool autoscalex_on: unknown autoscaley_on: unknown axes_locator: Callable[[Axes, Renderer], Bbox] axisbelow: bool or ‘line’ box_aspect: float or None clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None facecolor or fc: color figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure forward_navigation_events: bool or “auto” frame_on: bool gid: str in_layout: bool label: object mouseover: bool navigate: bool navigate_mode: unknown path_effects: list of .AbstractPathEffect picker: None or bool or float or callable position: [left, bottom, width, height] or ~matplotlib.transforms.Bbox prop_cycle: ~cycler.Cycler rasterization_zorder: float or None rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None subplotspec: unknown title: str transform: ~matplotlib.transforms.Transform url: str visible: bool xbound: (lower: float, upper: float) xlabel: str xlim: (left: float, right: float) xmargin: float greater than -0.5 xscale: unknown xticklabels: unknown xticks: unknown ybound: (lower: float, upper: float) ylabel: str ylim: (bottom: float, top: float) ymargin: float greater than -0.5 yscale: unknown yticklabels: unknown yticks: unknown zorder: float
- Returns:
The Axes of the subplot. The returned Axes can actually be an instance of a subclass, such as .projections.polar.PolarAxes for polar projections.
- Return type:
~.axes.Axes
Notes
Changed in version 3.8: In versions prior to 3.8, any preexisting Axes that overlap with the new Axes beyond sharing a boundary was deleted. Deletion does not happen in more recent versions anymore. Use .Axes.remove explicitly if needed.
If you do not want this behavior, use the .Figure.add_subplot method or the .pyplot.axes function instead.
If no kwargs are passed and there exists an Axes in the location specified by args then that Axes will be returned rather than a new Axes being created.
If kwargs are passed and there exists an Axes in the location specified by args, the projection type is the same, and the kwargs match with the existing Axes, then the existing Axes is returned. Otherwise a new Axes is created with the specified parameters. We save a reference to the kwargs which we use for this comparison. If any of the values in kwargs are mutable we will not detect the case where they are mutated. In these cases we suggest using .Figure.add_subplot and the explicit Axes API rather than the implicit pyplot API.
See also
Figure.add_subplot,pyplot.subplots,pyplot.axes,Figure.subplotsExamples
plt.subplot(221) # equivalent but more general ax1 = plt.subplot(2, 2, 1) # add a subplot with no frame ax2 = plt.subplot(222, frameon=False) # add a polar subplot plt.subplot(223, projection='polar') # add a red subplot that shares the x-axis with ax1 plt.subplot(224, sharex=ax1, facecolor='red') # delete ax2 from the figure plt.delaxes(ax2) # add ax2 to the figure again plt.subplot(ax2) # make the first Axes "current" again plt.subplot(221)
- scitex.plt.subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs)[source]
Create a subplot at a specific location inside a regular grid.
- Parameters:
shape ((int, int)) – Number of rows and of columns of the grid in which to place axis.
loc ((int, int)) – Row number and column number of the axis location within the grid.
rowspan (int, default: 1) – Number of rows for the axis to span downwards.
colspan (int, default: 1) – Number of columns for the axis to span to the right.
fig (.Figure, optional) – Figure to place the subplot in. Defaults to the current figure.
**kwargs – Additional keyword arguments are handed to ~.Figure.add_subplot.
- Returns:
The Axes of the subplot. The returned Axes can actually be an instance of a subclass, such as .projections.polar.PolarAxes for polar projections.
- Return type:
~.axes.Axes
Notes
The following call
ax = subplot2grid((nrows, ncols), (row, col), rowspan, colspan)
is identical to
fig = gcf() gs = fig.add_gridspec(nrows, ncols) ax = fig.add_subplot(gs[row:row+rowspan, col:col+colspan])
- scitex.plt.subplot_mosaic(mosaic, *, sharex=False, sharey=False, width_ratios=None, height_ratios=None, empty_sentinel='.', subplot_kw=None, gridspec_kw=None, per_subplot_kw=None, **fig_kw)[source]
Build a layout of Axes based on ASCII art or nested lists.
This is a helper function to build complex GridSpec layouts visually.
See Complex and semantic figure composition (subplot_mosaic) for an example and full API documentation
- Parameters:
mosaic (list of list of {hashable or nested} or str) –
A visual layout of how you want your Axes to be arranged labeled as strings. For example
x = [['A panel', 'A panel', 'edge'], ['C panel', '.', 'edge']]
produces 4 Axes:
’A panel’ which is 1 row high and spans the first two columns
’edge’ which is 2 rows high and is on the right edge
’C panel’ which in 1 row and 1 column wide in the bottom left
a blank space 1 row and 1 column wide in the bottom center
Any of the entries in the layout can be a list of lists of the same form to create nested layouts.
If input is a str, then it must be of the form
''' AAE C.E '''
where each character is a column and each line is a row. This only allows only single character Axes labels and does not allow nesting but is very terse.
sharex (bool, default: False) – If True, the x-axis (sharex) or y-axis (sharey) will be shared among all subplots. In that case, tick label visibility and axis units behave as for subplots. If False, each subplot’s x- or y-axis will be independent.
sharey (bool, default: False) – If True, the x-axis (sharex) or y-axis (sharey) will be shared among all subplots. In that case, tick label visibility and axis units behave as for subplots. If False, each subplot’s x- or y-axis will be independent.
width_ratios (array-like of length ncols, optional) – Defines the relative widths of the columns. Each column gets a relative width of
width_ratios[i] / sum(width_ratios). If not given, all columns will have the same width. Convenience forgridspec_kw={'width_ratios': [...]}.height_ratios (array-like of length nrows, optional) – Defines the relative heights of the rows. Each row gets a relative height of
height_ratios[i] / sum(height_ratios). If not given, all rows will have the same height. Convenience forgridspec_kw={'height_ratios': [...]}.empty_sentinel (object, optional) – Entry in the layout to mean “leave this space empty”. Defaults to
'.'. Note, if layout is a string, it is processed via inspect.cleandoc to remove leading white space, which may interfere with using white-space as the empty sentinel.subplot_kw (dict, optional) – Dictionary with keywords passed to the .Figure.add_subplot call used to create each subplot. These values may be overridden by values in per_subplot_kw.
per_subplot_kw (dict, optional) –
A dictionary mapping the Axes identifiers or tuples of identifiers to a dictionary of keyword arguments to be passed to the .Figure.add_subplot call used to create each subplot. The values in these dictionaries have precedence over the values in subplot_kw.
If mosaic is a string, and thus all keys are single characters, it is possible to use a single string instead of a tuple as keys; i.e.
"AB"is equivalent to("A", "B").Added in version 3.7.
gridspec_kw (dict, optional) – Dictionary with keywords passed to the .GridSpec constructor used to create the grid the subplots are placed on.
**fig_kw (Any) – All additional keyword arguments are passed to the .pyplot.figure call.
- Return type:
tuple[Figure, dict[str, matplotlib.axes.Axes]] | tuple[Figure, dict[_T, matplotlib.axes.Axes]] | tuple[Figure, dict[Hashable, matplotlib.axes.Axes]]
- Returns:
fig (.Figure) – The new figure
dict[label, Axes] – A dictionary mapping the labels to the Axes objects. The order of the Axes is left-to-right and top-to-bottom of their position in the total layout.
- scitex.plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)[source]
Adjust the subplot layout parameters.
Unset parameters are left unmodified; initial values are given by
rcParams[“figure.subplot.[name]”].- Parameters:
left (float, optional) – The position of the left edge of the subplots, as a fraction of the figure width.
right (float, optional) – The position of the right edge of the subplots, as a fraction of the figure width.
bottom (float, optional) – The position of the bottom edge of the subplots, as a fraction of the figure height.
top (float, optional) – The position of the top edge of the subplots, as a fraction of the figure height.
wspace (float, optional) – The width of the padding between subplots, as a fraction of the average Axes width.
hspace (float, optional) – The height of the padding between subplots, as a fraction of the average Axes height.
- Return type:
Notes
Note
This is the pyplot wrapper for .Figure.subplots_adjust.
- scitex.plt.tight_layout(*, pad=1.08, h_pad=None, w_pad=None, rect=None)[source]
Adjust the padding between and around subplots.
To exclude an artist on the Axes from the bounding box calculation that determines the subplot parameters (i.e. legend, or annotation), set
a.set_in_layout(False)for that artist.- Parameters:
pad (float, default: 1.08) – Padding between the figure edge and the edges of subplots, as a fraction of the font size.
h_pad (float, default: pad) – Padding (height/width) between edges of adjacent subplots, as a fraction of the font size.
w_pad (float, default: pad) – Padding (height/width) between edges of adjacent subplots, as a fraction of the font size.
rect (tuple (left, bottom, right, top), default: (0, 0, 1, 1)) – A rectangle in normalized figure coordinates into which the whole subplots area (including labels) will fit.
- Return type:
See also
Figure.set_layout_engine,pyplot.tight_layoutNotes
Note
This is the pyplot wrapper for .Figure.tight_layout.
- scitex.plt.suptitle(t, **kwargs)[source]
Add a centered super title to the figure.
- Parameters:
t (str) – The super title text.
x (float, default: 0.5) – The x location of the text in figure coordinates.
y (float, default: 0.98) – The y location of the text in figure coordinates.
horizontalalignment ({'center', 'left', 'right'}, default: center) – The horizontal alignment of the text relative to (x, y).
ha ({'center', 'left', 'right'}, default: center) – The horizontal alignment of the text relative to (x, y).
verticalalignment ({'top', 'center', 'bottom', 'baseline'}, default: top) – The vertical alignment of the text relative to (x, y).
va ({'top', 'center', 'bottom', 'baseline'}, default: top) – The vertical alignment of the text relative to (x, y).
fontsize (default:
rcParams[“figure.titlesize”](default:'large')) – The font size of the text. See .Text.set_size for possible values.size (default:
rcParams[“figure.titlesize”](default:'large')) – The font size of the text. See .Text.set_size for possible values.fontweight (default:
rcParams[“figure.titleweight”](default:'normal')) – The font weight of the text. See .Text.set_weight for possible values.weight (default:
rcParams[“figure.titleweight”](default:'normal')) – The font weight of the text. See .Text.set_weight for possible values.fontproperties (None or dict, optional) – A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the .FontProperties defaults.
rcParams[“figure.titlesize”](default:'large') andrcParams[“figure.titleweight”](default:'normal') are ignored in this case.**kwargs – Additional kwargs are matplotlib.text.Text properties.
- Returns:
The .Text instance of the super title.
- Return type:
text
Notes
Note
This is the pyplot wrapper for .Figure.suptitle.
- scitex.plt.xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)[source]
Set the label for the x-axis.
- Parameters:
xlabel (str) – The label text.
labelpad (float, default:
rcParams[“axes.labelpad”](default:4.0)) – 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:
rcParams[“xaxis.labellocation”](default:'center')) – The label position. This is a high-level alternative for passing parameters x and horizontalalignment.**kwargs (~matplotlib.text.Text properties) – .Text properties control the appearance of the label.
- Return type:
See also
textDocuments the properties supported by .Text.
Notes
Note
This is the pyplot wrapper for .axes.Axes.set_xlabel.
- scitex.plt.ylabel(ylabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)[source]
Set the label for the y-axis.
- Parameters:
ylabel (str) – The label text.
labelpad (float, default:
rcParams[“axes.labelpad”](default:4.0)) – 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:
rcParams[“yaxis.labellocation”](default:'center')) – The label position. This is a high-level alternative for passing parameters y and horizontalalignment.**kwargs (~matplotlib.text.Text properties) – .Text properties control the appearance of the label.
- Return type:
See also
textDocuments the properties supported by .Text.
Notes
Note
This is the pyplot wrapper for .axes.Axes.set_ylabel.
- scitex.plt.title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)[source]
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) –
Discouraged
The use of fontdict is discouraged. Parameters should be passed as individual keyword arguments or using dictionary-unpacking
set_title(..., **fontdict).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:
rcParams[“axes.titlelocation”](default:'center')) – Which title to set.y (float, default:
rcParams[“axes.titley”](default:None)) – Vertical Axes location for the title (1.0 is the top). If None (the default) andrcParams[“axes.titley”](default:None) is also None, y is determined automatically to avoid decorators on the Axes.pad (float, default:
rcParams[“axes.titlepad”](default:6.0)) – The offset of the title from the top of the Axes, in points.**kwargs (~matplotlib.text.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
Notes
Note
This is the pyplot wrapper for .axes.Axes.set_title.
- scitex.plt.legend(*args, **kwargs)[source]
Place a legend on the Axes.
Call signatures:
legend() legend(handles, labels) legend(handles=handles) legend(labels)
The call signatures correspond to the following different ways to use this method:
1. Automatic detection of elements to be shown in the legend
The elements to be added to the legend are automatically determined, when you do not pass in any extra arguments.
In this case, the labels are taken from the artist. You can specify them either at artist creation or by calling the
set_label()method on the artist:ax.plot([1, 2, 3], label='Inline label') ax.legend()
or:
line, = ax.plot([1, 2, 3]) line.set_label('Label via method') ax.legend()
Note
Specific artists can be excluded from the automatic legend element selection by using a label starting with an underscore, “_”. A string starting with an underscore is the default label for all artists, so calling .Axes.legend without any arguments and without setting the labels manually will result in a
UserWarningand an empty legend being drawn.2. Explicitly listing the artists and labels in the legend
For full control of which artists have a legend entry, it is possible to pass an iterable of legend artists followed by an iterable of legend labels respectively:
ax.legend([line1, line2, line3], ['label1', 'label2', 'label3'])
3. Explicitly listing the artists in the legend
This is similar to 2, but the labels are taken from the artists’ label properties. Example:
line1, = ax.plot([1, 2, 3], label='label1') line2, = ax.plot([1, 2, 3], label='label2') ax.legend(handles=[line1, line2])
4. Labeling existing plot elements
Discouraged
This call signature is discouraged, because the relation between plot elements and labels is only implicit by their order and can easily be mixed up.
To make a legend for all artists on an Axes, call this function with an iterable of strings, one for each legend item. For example:
ax.plot([1, 2, 3]) ax.plot([5, 6, 7]) ax.legend(['First line', 'Second line'])
- Parameters:
handles (list of (.Artist or tuple 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.
If an entry contains a tuple, then the legend handler for all Artists in the tuple will be placed alongside a single label.
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:
rcParams[“legend.loc”](default:'best')) –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.The strings
'upper center','lower center','center left','center right'place the legend at the center of the corresponding edge of the axes.The string
'center'places the legend at the center of the axes.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” location can also be given as a numeric value:Location String
Location Code
’best’ (Axes only)
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) orfigure.bbox(iffigure.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
legendis 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)
ncols (int, default: 1) –
The number of columns that the legend has.
For backward compatibility, the spelling ncol is also supported but it is discouraged. If both are given, ncols takes precedence.
prop (None or ~matplotlib.font_manager.FontProperties or dict) – The font properties of the legend. If None (default), the current
matplotlib.rcParamswill 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, default:
rcParams[“legend.labelcolor”](default:'None')) –The color of the text in the legend. Either a valid color string (for example, ‘red’), or a list of color strings. The labelcolor can also be made to match the color of the line or marker using ‘linecolor’, ‘markerfacecolor’ (or ‘mfc’), or ‘markeredgecolor’ (or ‘mec’).
Labelcolor can be set globally using
rcParams[“legend.labelcolor”](default:'None'). If None, usercParams[“text.color”](default:'black').numpoints (int, default:
rcParams[“legend.numpoints”](default:1)) – The number of marker points in the legend when creating a legend entry for a .Line2D (line).scatterpoints (int, default:
rcParams[“legend.scatterpoints”](default:1)) – 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:
rcParams[“legend.markerscale”](default:1.0)) – The relative size of legend markers compared to 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.
reverse (bool, default: False) –
If True, the legend labels are displayed in reverse order from the input. If False, the legend labels are displayed in the same order as the input.
Added in version 3.7.
frameon (bool, default:
rcParams[“legend.frameon”](default:True)) – Whether the legend should be drawn on a patch (frame).fancybox (bool, default:
rcParams[“legend.fancybox”](default:True)) – Whether round edges should be enabled around the .FancyBboxPatch which makes up the legend’s background.shadow (None, bool or dict, default:
rcParams[“legend.shadow”](default:False)) – Whether to draw a shadow behind the legend. The shadow can be configured using .Patch keywords. Customization viarcParams[“legend.shadow”](default:False) is currently not supported.framealpha (float, default:
rcParams[“legend.framealpha”](default:0.8)) – The alpha transparency of the legend’s background. If shadow is activated and framealpha isNone, the default value is ignored.facecolor (“inherit” or color, default:
rcParams[“legend.facecolor”](default:'inherit')) – The legend’s background color. If"inherit", usercParams[“axes.facecolor”](default:'white').edgecolor (“inherit” or color, default:
rcParams[“legend.edgecolor”](default:'0.8')) – The legend’s background patch edge color. If"inherit", usercParams[“axes.edgecolor”](default:'black').mode ({"expand", None}) – If mode is set to
"expand"the legend will be horizontally expanded to fill the Axes area (or bbox_to_anchor if defines the legend’s size).bbox_transform (None or ~matplotlib.transforms.Transform) – The transform for the bounding box (bbox_to_anchor). For a value of
None(default) the Axes’transAxestransform will be used.title (str or None) – The legend’s title. Default is no title (
None).title_fontproperties (None or ~matplotlib.font_manager.FontProperties or dict) – The font properties of the legend’s title. If None (default), the title_fontsize argument will be used if present; if title_fontsize is also None, the current
rcParams[“legend.title_fontsize”](default:None) will be used.title_fontsize (int or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}, default:
rcParams[“legend.title_fontsize”](default:None)) – The font size of the legend’s title. Note: This cannot be combined with title_fontproperties. If you want to set the fontsize alongside other font properties, use the size parameter in title_fontproperties.alignment ({'center', 'left', 'right'}, default: 'center') – The alignment of the legend title and the box of entries. The entries are aligned as a single block, so that markers always lined up.
borderpad (float, default:
rcParams[“legend.borderpad”](default:0.4)) – The fractional whitespace inside the legend border, in font-size units.labelspacing (float, default:
rcParams[“legend.labelspacing”](default:0.5)) – The vertical space between the legend entries, in font-size units.handlelength (float, default:
rcParams[“legend.handlelength”](default:2.0)) – The length of the legend handles, in font-size units.handleheight (float, default:
rcParams[“legend.handleheight”](default:0.7)) – The height of the legend handles, in font-size units.handletextpad (float, default:
rcParams[“legend.handletextpad”](default:0.8)) – The pad between the legend handle and text, in font-size units.borderaxespad (float, default:
rcParams[“legend.borderaxespad”](default:0.5)) – The pad between the Axes and legend border, in font-size units.columnspacing (float, default:
rcParams[“legend.columnspacing”](default:2.0)) – 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.
draggable (bool, default: False) – Whether the legend can be dragged with the mouse.
- Return type:
~matplotlib.legend.Legend
See also
Figure.legendNotes
Note
This is the pyplot wrapper for .axes.Axes.legend.
Some artists are not supported by this function. See Legend guide for details.
Examples
- scitex.plt.xlim(*args, **kwargs)[source]
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.
- scitex.plt.ylim(*args, **kwargs)[source]
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.
- scitex.plt.grid(visible=None, which='major', axis='both', **kwargs)[source]
Configure the grid lines.
- Parameters:
visible (bool or None, optional) –
Whether to show the grid lines. If any kwargs are supplied, it is assumed you want the grid on and visible will be set to True.
If visible is None and there are no kwargs, this toggles the visibility of the lines.
which ({'major', 'minor', 'both'}, optional) – The grid lines to apply the changes on.
axis ({'both', 'x', 'y'}, optional) – The axis to apply the changes on.
**kwargs (~matplotlib.lines.Line2D properties) –
Define the line properties of the grid, e.g.:
grid(color='r', linestyle='-', linewidth=2)
Valid keyword arguments are:
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 and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color 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: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: color or 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] mouseover: bool path_effects: list of .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: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float
- Return type:
Notes
Note
This is the pyplot wrapper for .axes.Axes.grid.
The axis is drawn as a unit, so the effective zorder for drawing the grid is determined by the zorder of each axis, not by the zorder of the .Line2D objects comprising the grid. Therefore, to set grid zorder, use .set_axisbelow or, for more control, call the ~.Artist.set_zorder method of each axis.
- scitex.plt.plot(*args, scalex=True, scaley=True, data=None, **kwargs)[source]
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
rcParams[“axes.prop_cycle”](default:cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])).- Parameters:
x (array-like or float) –
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 float) –
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 beplt(x, y)orplt(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 stringplot('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 ~.axes.Axes.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 ~.axes.Axes.autoscale_view.
**kwargs (~matplotlib.lines.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 and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color 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: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: color or 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] mouseover: bool path_effects: list of .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: unknown 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
scatterXY scatter plot with markers of varying size and/or color ( sometimes also called bubble chart).
Notes
Note
This is the pyplot wrapper for .axes.Axes.plot.
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
lineis given, but nomarker, 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').
- scitex.plt.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, *, edgecolors=None, colorizer=None, plotnonfinite=False, data=None, **kwargs)[source]
A scatter plot of y vs. x with varying marker size and/or color.
- Parameters:
s (float or array-like, shape (n, ), optional) –
The marker size in points**2 (typographic points are 1/72 in.). Default is
rcParams['lines.markersize'] ** 2.The linewidth and edgecolor can visually interact with the marker size, and can lead to artifacts if the marker size is smaller than the linewidth.
If the linewidth is greater than 0 and the edgecolor is anything but ‘none’, then the effective size of the marker will be increased by half the linewidth because the stroke will be centered on the edge of the shape.
To eliminate the marker edge either set linewidth=0 or edgecolor=’none’.
c (array-like or list of color 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 torcParams[“axes.prop_cycle”](default:cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])).marker (~.markers.MarkerStyle, default:
rcParams[“scatter.marker”](default:'o')) – The marker style. marker can be either an instance of the class or the text shorthand for a particular marker. Seematplotlib.markersfor more information about marker styles.cmap (str or ~matplotlib.colors.Colormap, default:
rcParams[“image.cmap”](default:'viridis')) –The Colormap instance or registered colormap name used to map scalar data to colors.
This parameter is ignored if c is RGB(A).
norm (str or ~matplotlib.colors.Normalize, optional) –
The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.
If given, this can be one of the following:
An instance of .Normalize or one of its subclasses (see Colormap normalization).
A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.
This parameter is ignored if c is RGB(A).
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
This parameter is ignored if c is RGB(A).
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
This parameter is ignored if c is RGB(A).
alpha (float, default: None) – The alpha blending value, between 0 (transparent) and 1 (opaque).
linewidths (float or array-like, default:
rcParams[“lines.linewidth”](default:1.5)) – 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 list of color, default:
rcParams[“scatter.edgecolors”](default:'face')) –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.
colorizer (~matplotlib.colorizer.Colorizer or None, default: None) –
The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.
This parameter is ignored if c is RGB(A).
plotnonfinite (bool, default: False) – Whether to plot points with nonfinite c (i.e.
inf,-infornan). IfTruethe points are drawn with the bad colormap color (see .Colormap.set_bad).data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x, y, s, linewidths, edgecolors, c, facecolor, facecolors, color
**kwargs (~matplotlib.collections.PathCollection 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 and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased or aa or antialiaseds: bool or list of bools array: array-like or None capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clim: (vmin: float, vmax: float) clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: color or list of RGBA tuples edgecolor or ec or edgecolors: color or list of color or ‘face’ facecolor or facecolors or fc: color or list of color figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown 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 mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .AbstractPathEffect paths: unknown picker: None or bool or float or callable pickradius: float rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str urls: list of str or None visible: bool zorder: float
- Return type:
~matplotlib.collections.PathCollection
See also
plotTo plot scatter plots when markers are identical in size and color.
Notes
Note
This is the pyplot wrapper for .axes.Axes.scatter.
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.
- scitex.plt.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)[source]
Make a bar plot.
The bars are positioned at x with the given alignment. Their dimensions are given by height and width. The vertical baseline is bottom (default 0).
Many parameters can take either a single value applying to all bars or a sequence of values, one for each bar.
- Parameters:
x (float or array-like) –
The x coordinates of the bars. See also align for the alignment of the bars to the coordinates.
Bars are often used for categorical data, i.e. string labels below the bars. You can provide a list of strings directly to x.
bar(['A', 'B', 'C'], [1, 2, 3])is often a shorter and more convenient notation compared tobar(range(3), [1, 2, 3], tick_label=['A', 'B', 'C']). They are equivalent as long as the names are unique. The explicit tick_label notation draws the names in the sequence given. However, when having duplicate values in categorical x data, these values map to the same numerical x coordinate, and hence the corresponding bars are drawn on top of each other.height (float or array-like) –
The height(s) of the bars.
Note that if bottom has units (e.g. datetime), height should be in units that are a difference from the value of bottom (e.g. timedelta).
width (float or array-like, default: 0.8) –
The width(s) of the bars.
Note that if x has units (e.g. datetime), then width should be in units that are a difference (e.g. timedelta) around the x values.
bottom (float or array-like, default: 0) –
The y coordinate(s) of the bottom side(s) of the bars.
Note that if bottom has units, then the y-axis will get a Locator and Formatter appropriate for the units (e.g. dates, or categorical).
align ({'center', 'edge'}, default: 'center') –
Alignment of the bars to the x coordinates:
’center’: Center the base on the x positions.
’edge’: Align the left edges of the bars with the x positions.
To align the bars on the right edge pass a negative width and
align='edge'.color (color or list of color, optional) – The colors of the bar faces. This is an alias for facecolor. If both are given, facecolor takes precedence.
facecolor (color or list of color, optional) – The colors of the bar faces. If both color and facecolor are given, *facecolor takes precedence.
edgecolor (color or list of color, optional) – The colors of the bar edges.
linewidth (float or array-like, optional) – Width of the bar edge(s). If 0, don’t draw edges.
tick_label (str or list of str, optional) – The tick labels of the bars. Default: None (Use default numeric labels.)
label (str or list of str, optional) – A single label is attached to the resulting .BarContainer as a label for the whole dataset. If a list is provided, it must be the same length as x and labels the individual bars. Repeated labels are not de-duplicated and will cause repeated label entries, so this is best used when bars also differ in style (e.g., by passing a list to color.)
xerr (float or array-like of shape(N,) or shape(2, N), optional) –
If not None, add horizontal / vertical errorbars to the bar tips. The values are +/- sizes relative to the data:
scalar: symmetric +/- values for all bars
shape(N,): symmetric +/- values for each bar
shape(2, N): Separate - and + values for each bar. First row contains the lower errors, the second row contains the upper errors.
None: No errorbar. (Default)
See /gallery/statistics/errorbar_features for an example on the usage of xerr and yerr.
yerr (float or array-like of shape(N,) or shape(2, N), optional) –
If not None, add horizontal / vertical errorbars to the bar tips. The values are +/- sizes relative to the data:
scalar: symmetric +/- values for all bars
shape(N,): symmetric +/- values for each bar
shape(2, N): Separate - and + values for each bar. First row contains the lower errors, the second row contains the upper errors.
None: No errorbar. (Default)
See /gallery/statistics/errorbar_features for an example on the usage of xerr and yerr.
ecolor (color or list of color, default: ‘black’) – The line color of the errorbars.
capsize (float, default:
rcParams[“errorbar.capsize”](default:0.0)) – The length of the error bar caps in points.error_kw (dict, optional) – Dictionary of keyword arguments to be passed to the ~.Axes.errorbar method. Values of ecolor or capsize defined here take precedence over the independent keyword arguments.
log (bool, default: False) – If True, set the y-axis to be log scale.
data (indexable object, optional) – If given, all parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata.**kwargs (.Rectangle 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 and two offsets from the bottom left corner of the image alpha: float or None angle: unknown animated: bool antialiased or aa: bool or None bounds: (left, bottom, width, height) capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color: color edgecolor or ec: color or None facecolor or fc: color or None figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fill: bool gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown height: unknown in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float or None mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str visible: bool width: unknown x: unknown xy: (float, float) y: unknown zorder: float
- Returns:
Container with all the bars and optionally errorbars.
- Return type:
.BarContainer
See also
barhPlot a horizontal bar plot.
Notes
Note
This is the pyplot wrapper for .axes.Axes.bar.
Stacked bars can be achieved by passing individual bottom values per bar. See /gallery/lines_bars_and_markers/bar_stacked.
- scitex.plt.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, *, data=None, **kwargs)[source]
Compute and plot a histogram.
This method uses numpy.histogram to bin the data in x and count the number of values in each bin, then draws the distribution either as a .BarContainer or .Polygon. The bins, range, density, and weights parameters are forwarded to numpy.histogram.
If the data has already been binned and counted, use ~.bar or ~.stairs to plot the distribution:
counts, bins = np.histogram(x) plt.stairs(counts, bins)
Alternatively, plot pre-computed bins and counts using
hist()by treating each bin as a single point with a weight equal to its count:plt.hist(bins[:-1], bins, weights=counts)
The data input x can be a singular array, a list of datasets of potentially different lengths ([x0, x1, …]), or a 2D ndarray in which each column is a dataset. Note that the ndarray form is transposed relative to the list form. If the input is an array, then the return value is a tuple (n, bins, patches); if the input is a sequence of arrays, then the return value is a tuple ([n0, n1, …], bins, [patches0, patches1, …]).
Masked arrays are not supported.
- 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:
rcParams[“hist.bins”](default:10)) –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.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
Truethen 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 or float, default: 0) – Location of the bottom of each bin, i.e. bins are drawn from
bottomtobottom + 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 list of color or None, default: None) – Color or sequence of colors, one per dataset. Default (
None) uses the standard line color sequence.label (str or list of str, optional) – 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 IfFalsemultiple data are arranged side by side if histtype is ‘bar’ or on top of each other if histtype is ‘step’data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x, weights
**kwargs –
~matplotlib.patches.Patch properties. The following properties additionally accept a sequence of values corresponding to the datasets in x: edgecolor, facecolor, linewidth, linestyle, hatch.
Added in version 3.10: Allowing sequences of values in above listed Patch properties.
- Return type:
tuple[ndarray|list[ndarray],ndarray,BarContainer|Polygon|list[BarContainer|Polygon]]- 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
Notes
Note
This is the pyplot wrapper for .axes.Axes.hist.
For large numbers of bins (>1000), plotting can be significantly accelerated by using ~.Axes.stairs to plot a pre-computed histogram (
plt.stairs(*np.histogram(data))), or by setting histtype to ‘step’ or ‘stepfilled’ rather than ‘bar’ or ‘barstacked’.
- scitex.plt.imshow(X, cmap=None, norm=None, *, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, colorizer=None, origin=None, extent=None, interpolation_stage=None, filternorm=True, filterrad=4.0, resample=None, url=None, data=None, **kwargs)[source]
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 figure dpi. 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
rcParams[“image.interpolation”](default:'auto').- 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:
rcParams[“image.cmap”](default:'viridis')) –The Colormap instance or registered colormap name used to map scalar data to colors.
This parameter is ignored if X is RGB(A).
norm (str or ~matplotlib.colors.Normalize, optional) –
The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.
If given, this can be one of the following:
An instance of .Normalize or one of its subclasses (see Colormap normalization).
A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.
This parameter is ignored if X is RGB(A).
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
This parameter is ignored if X is RGB(A).
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
This parameter is ignored if X is RGB(A).
colorizer (~matplotlib.colorizer.Colorizer or None, default: None) –
The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.
This parameter is ignored if X is RGB(A).
aspect ({'equal', 'auto'} or float or None, default: None) –
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.
Normally, None (the default) means to use
rcParams[“image.aspect”](default:'equal'). However, if the image uses a transform that does not contain the axes data transform, then None means to not modify the axes aspect at all (in that case, directly call .Axes.set_aspect if desired).interpolation (str, default:
rcParams[“image.interpolation”](default:'auto')) –The interpolation method used.
Supported values are ‘none’, ‘auto’, ‘nearest’, ‘bilinear’, ‘bicubic’, ‘spline16’, ‘spline36’, ‘hanning’, ‘hamming’, ‘hermite’, ‘kaiser’, ‘quadric’, ‘catrom’, ‘gaussian’, ‘bessel’, ‘mitchell’, ‘sinc’, ‘lanczos’, ‘blackman’.
The data X is resampled to the pixel size of the image on the figure canvas, using the interpolation method to either up- or downsample the data.
If interpolation is ‘none’, then for the ps, pdf, and svg backends no down- or upsampling occurs, and the image data is passed to the backend as a native image. Note that different ps, pdf, and svg viewers may display these raw pixels differently. On other backends, ‘none’ is the same as ‘nearest’.
If interpolation is the default ‘auto’, 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.
interpolation_stage ({'auto', 'data', 'rgba'}, default: 'auto') –
Supported values:
’data’: Interpolation is carried out on the data provided by the user This is useful if interpolating between pixels during upsampling.
’rgba’: The interpolation is carried out in RGBA-space after the color-mapping has been applied. This is useful if downsampling and combining pixels visually.
’auto’: Select a suitable interpolation stage automatically. This uses ‘rgba’ when downsampling, or upsampling at a rate less than 3, and ‘data’ when upsampling at a higher rate.
See /gallery/images_contours_and_fields/image_antialiasing for a discussion of image antialiasing.
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.
origin ({‘upper’, ‘lower’}, default:
rcParams[“image.origin”](default:'upper')) –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 origin and extent in imshow 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. These values may be unitful and match the units of the Axes. 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 origin and extent in imshow 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:
rcParams[“image.resample”](default:True)) – 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.
data (indexable object, optional) – If given, all parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata.**kwargs (~matplotlib.artist.Artist properties) – These parameters are passed on to the constructor of the .AxesImage artist.
- Return type:
~matplotlib.image.AxesImage
See also
matshowPlot a matrix or an array as an image.
Notes
Note
This is the pyplot wrapper for .axes.Axes.imshow.
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.
- scitex.plt.contour(*args, data=None, **kwargs)[source]
Plot contour lines.
Call signature:
contour([X, Y,] Z, /, [levels], **kwargs)
The arguments X, Y, Z are positional-only.
.contour and .contourf draw contour lines and filled contours, respectively. Except as noted, function signatures and return values are the same for both versions.
- Parameters:
X (array-like, optional) –
The coordinates of the values in Z.
X and Y must both be 2D with the same shape as Z (e.g. created via numpy.meshgrid), or they must both be 1-D such that
len(X) == Nis the number of columns in Z andlen(Y) == Mis the number of rows in Z.X and Y must both be ordered monotonically.
If not given, they are assumed to be integer indices, i.e.
X = range(N),Y = range(M).Y (array-like, optional) –
The coordinates of the values in Z.
X and Y must both be 2D with the same shape as Z (e.g. created via numpy.meshgrid), or they must both be 1-D such that
len(X) == Nis the number of columns in Z andlen(Y) == Mis the number of rows in Z.X and Y must both be ordered monotonically.
If not given, they are assumed to be integer indices, i.e.
X = range(N),Y = range(M).Z ((M, N) array-like) – The height values over which the contour is drawn. Color-mapping is controlled by cmap, norm, vmin, and vmax.
levels (int or array-like, optional) –
Determines the number and positions of the contour lines / regions.
If an int n, use ~matplotlib.ticker.MaxNLocator, which tries to automatically choose no more than n+1 “nice” contour levels between minimum and maximum numeric values of Z.
If array-like, draw contour lines at the specified levels. The values must be in increasing order.
corner_mask (bool, default:
rcParams[“contour.corner_mask”](default:True)) – Enable/disable corner masking, which only has an effect if Z is a masked array. IfFalse, any quad touching a masked point is masked out. IfTrue, only the triangular corners of quads nearest those points are always masked out, other triangular corners comprising three unmasked points are contoured as usual.colors (color or list of color, optional) –
The colors of the levels, i.e. the lines for .contour and the areas for .contourf.
The sequence is cycled for the levels in ascending order. If the sequence is shorter than the number of levels, it’s repeated.
As a shortcut, a single color may be used in place of one-element lists, i.e.
'red'instead of['red']to color all levels with the same color.Changed in version 3.10: Previously a single color had to be expressed as a string, but now any valid color format may be passed.
By default (value None), the colormap specified by cmap will be used.
alpha (float, default: 1) – The alpha blending value, between 0 (transparent) and 1 (opaque).
cmap (str or ~matplotlib.colors.Colormap, default:
rcParams[“image.cmap”](default:'viridis')) –The Colormap instance or registered colormap name used to map scalar data to colors.
This parameter is ignored if colors is set.
norm (str or ~matplotlib.colors.Normalize, optional) –
The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.
If given, this can be one of the following:
An instance of .Normalize or one of its subclasses (see Colormap normalization).
A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.
This parameter is ignored if colors is set.
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
If vmin or vmax are not given, the default color scaling is based on levels.
This parameter is ignored if colors is set.
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
If vmin or vmax are not given, the default color scaling is based on levels.
This parameter is ignored if colors is set.
colorizer (~matplotlib.colorizer.Colorizer or None, default: None) –
The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.
This parameter is ignored if colors is set.
origin ({None, ‘upper’, ‘lower’, ‘image’}, default: None) –
Determines the orientation and exact position of Z by specifying the position of
Z[0, 0]. This is only relevant, if X, Y are not given.None:
Z[0, 0]is at X=0, Y=0 in the lower left corner.’lower’:
Z[0, 0]is at X=0.5, Y=0.5 in the lower left corner.’upper’:
Z[0, 0]is at X=N+0.5, Y=0.5 in the upper left corner.’image’: Use the value from
rcParams[“image.origin”](default:'upper').
extent ((x0, x1, y0, y1), optional) –
If origin is not None, then extent is interpreted as in .imshow: it gives the outer pixel boundaries. In this case, the position of Z[0, 0] is the center of the pixel, not a corner. If origin is None, then (x0, y0) is the position of Z[0, 0], and (x1, y1) is the position of Z[-1, -1].
This argument is ignored if X and Y are specified in the call to contour.
locator (ticker.Locator subclass, optional) – The locator is used to determine the contour levels if they are not given explicitly via levels. Defaults to ~.ticker.MaxNLocator.
extend ({'neither', 'both', 'min', 'max'}, default: 'neither') –
Determines the
contourf-coloring of values that are outside the levels range.If ‘neither’, values outside the levels range are not colored. If ‘min’, ‘max’ or ‘both’, color the values below, above or below and above the levels range.
Values below
min(levels)and abovemax(levels)are mapped to the under/over values of the .Colormap. Note that most colormaps do not have dedicated colors for these by default, so that the over and under values are the edge values of the colormap. You may want to set these values explicitly using .Colormap.set_under and .Colormap.set_over.Note
An existing .QuadContourSet does not get notified if properties of its colormap are changed. Therefore, an explicit call ~.ContourSet.changed() is needed after modifying the colormap. The explicit call can be left out, if a colorbar is assigned to the .QuadContourSet because it internally calls ~.ContourSet.changed().
Example:
x = np.arange(1, 10) y = x.reshape(-1, 1) h = x * y cs = plt.contourf(h, levels=[10, 30, 50], colors=['#808080', '#A0A0A0', '#C0C0C0'], extend='both') cs.cmap.set_over('red') cs.cmap.set_under('blue') cs.changed()
xunits (registered units, optional) – Override axis units by specifying an instance of a
matplotlib.units.ConversionInterface.yunits (registered units, optional) – Override axis units by specifying an instance of a
matplotlib.units.ConversionInterface.antialiased (bool, optional) – Enable antialiasing, overriding the defaults. For filled contours, the default is False. For line contours, it is taken from
rcParams[“lines.antialiased”](default:True).nchunk (int >= 0, optional) – If 0, no subdivision of the domain. Specify a positive integer to divide the domain into subdomains of nchunk by nchunk quads. Chunking reduces the maximum length of polygons generated by the contouring algorithm which reduces the rendering workload passed on to the backend and also requires slightly less RAM. It can however introduce rendering artifacts at chunk boundaries depending on the backend, the antialiased flag and value of alpha.
linewidths (float or array-like, default:
rcParams[“contour.linewidth”](default:None)) –Only applies to .contour.
The line width of the contour lines.
If a number, all levels will be plotted with this linewidth.
If a sequence, the levels in ascending order will be plotted with the linewidths in the order specified.
If None, this falls back to
rcParams[“lines.linewidth”](default:1.5).linestyles ({None, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’}, optional) –
Only applies to .contour.
If linestyles is None, the default is ‘solid’ unless the lines are monochrome. In that case, negative contours will instead take their linestyle from the negative_linestyles argument.
linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary.
negative_linestyles ({None, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’}, optional) –
Only applies to .contour.
If linestyles is None and the lines are monochrome, this argument specifies the line style for negative contours.
If negative_linestyles is None, the default is taken from
rcParams[“contour.negative_linestyle”](default:'dashed').negative_linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary.
hatches (list[str], optional) –
Only applies to .contourf.
A list of cross hatch patterns to use on the filled areas. If None, no hatching will be added to the contour.
algorithm ({'mpl2005', 'mpl2014', 'serial', 'threaded'}, optional) –
Which contouring algorithm to use to calculate the contour lines and polygons. The algorithms are implemented in ContourPy, consult the ContourPy documentation for further information.
The default is taken from
rcParams[“contour.algorithm”](default:'mpl2014').clip_path (~matplotlib.patches.Patch or .Path or .TransformedPath) –
Set the clip path. See ~matplotlib.artist.Artist.set_clip_path.
Added in version 3.8.
data (indexable object, optional) – If given, all parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata.
- Return type:
~.contour.QuadContourSet
Notes
Note
This is the pyplot wrapper for .axes.Axes.contour.
.contourf differs from the MATLAB version in that it does not draw the polygon edges. To draw edges, add line contours with calls to .contour.
.contourf fills intervals that are closed at the top; that is, for boundaries z1 and z2, the filled region is:
z1 < Z <= z2
except for the lowest interval, which is closed on both sides (i.e. it includes the lowest value).
.contour and .contourf use a marching squares algorithm to compute contour locations. More information can be found in ContourPy documentation.
- scitex.plt.contourf(*args, data=None, **kwargs)[source]
Plot filled contours.
Call signature:
contourf([X, Y,] Z, /, [levels], **kwargs)
The arguments X, Y, Z are positional-only.
.contour and .contourf draw contour lines and filled contours, respectively. Except as noted, function signatures and return values are the same for both versions.
- Parameters:
X (array-like, optional) –
The coordinates of the values in Z.
X and Y must both be 2D with the same shape as Z (e.g. created via numpy.meshgrid), or they must both be 1-D such that
len(X) == Nis the number of columns in Z andlen(Y) == Mis the number of rows in Z.X and Y must both be ordered monotonically.
If not given, they are assumed to be integer indices, i.e.
X = range(N),Y = range(M).Y (array-like, optional) –
The coordinates of the values in Z.
X and Y must both be 2D with the same shape as Z (e.g. created via numpy.meshgrid), or they must both be 1-D such that
len(X) == Nis the number of columns in Z andlen(Y) == Mis the number of rows in Z.X and Y must both be ordered monotonically.
If not given, they are assumed to be integer indices, i.e.
X = range(N),Y = range(M).Z ((M, N) array-like) – The height values over which the contour is drawn. Color-mapping is controlled by cmap, norm, vmin, and vmax.
levels (int or array-like, optional) –
Determines the number and positions of the contour lines / regions.
If an int n, use ~matplotlib.ticker.MaxNLocator, which tries to automatically choose no more than n+1 “nice” contour levels between minimum and maximum numeric values of Z.
If array-like, draw contour lines at the specified levels. The values must be in increasing order.
corner_mask (bool, default:
rcParams[“contour.corner_mask”](default:True)) – Enable/disable corner masking, which only has an effect if Z is a masked array. IfFalse, any quad touching a masked point is masked out. IfTrue, only the triangular corners of quads nearest those points are always masked out, other triangular corners comprising three unmasked points are contoured as usual.colors (color or list of color, optional) –
The colors of the levels, i.e. the lines for .contour and the areas for .contourf.
The sequence is cycled for the levels in ascending order. If the sequence is shorter than the number of levels, it’s repeated.
As a shortcut, a single color may be used in place of one-element lists, i.e.
'red'instead of['red']to color all levels with the same color.Changed in version 3.10: Previously a single color had to be expressed as a string, but now any valid color format may be passed.
By default (value None), the colormap specified by cmap will be used.
alpha (float, default: 1) – The alpha blending value, between 0 (transparent) and 1 (opaque).
cmap (str or ~matplotlib.colors.Colormap, default:
rcParams[“image.cmap”](default:'viridis')) –The Colormap instance or registered colormap name used to map scalar data to colors.
This parameter is ignored if colors is set.
norm (str or ~matplotlib.colors.Normalize, optional) –
The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.
If given, this can be one of the following:
An instance of .Normalize or one of its subclasses (see Colormap normalization).
A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.
This parameter is ignored if colors is set.
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
If vmin or vmax are not given, the default color scaling is based on levels.
This parameter is ignored if colors is set.
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
If vmin or vmax are not given, the default color scaling is based on levels.
This parameter is ignored if colors is set.
colorizer (~matplotlib.colorizer.Colorizer or None, default: None) –
The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.
This parameter is ignored if colors is set.
origin ({None, ‘upper’, ‘lower’, ‘image’}, default: None) –
Determines the orientation and exact position of Z by specifying the position of
Z[0, 0]. This is only relevant, if X, Y are not given.None:
Z[0, 0]is at X=0, Y=0 in the lower left corner.’lower’:
Z[0, 0]is at X=0.5, Y=0.5 in the lower left corner.’upper’:
Z[0, 0]is at X=N+0.5, Y=0.5 in the upper left corner.’image’: Use the value from
rcParams[“image.origin”](default:'upper').
extent ((x0, x1, y0, y1), optional) –
If origin is not None, then extent is interpreted as in .imshow: it gives the outer pixel boundaries. In this case, the position of Z[0, 0] is the center of the pixel, not a corner. If origin is None, then (x0, y0) is the position of Z[0, 0], and (x1, y1) is the position of Z[-1, -1].
This argument is ignored if X and Y are specified in the call to contour.
locator (ticker.Locator subclass, optional) – The locator is used to determine the contour levels if they are not given explicitly via levels. Defaults to ~.ticker.MaxNLocator.
extend ({'neither', 'both', 'min', 'max'}, default: 'neither') –
Determines the
contourf-coloring of values that are outside the levels range.If ‘neither’, values outside the levels range are not colored. If ‘min’, ‘max’ or ‘both’, color the values below, above or below and above the levels range.
Values below
min(levels)and abovemax(levels)are mapped to the under/over values of the .Colormap. Note that most colormaps do not have dedicated colors for these by default, so that the over and under values are the edge values of the colormap. You may want to set these values explicitly using .Colormap.set_under and .Colormap.set_over.Note
An existing .QuadContourSet does not get notified if properties of its colormap are changed. Therefore, an explicit call ~.ContourSet.changed() is needed after modifying the colormap. The explicit call can be left out, if a colorbar is assigned to the .QuadContourSet because it internally calls ~.ContourSet.changed().
Example:
x = np.arange(1, 10) y = x.reshape(-1, 1) h = x * y cs = plt.contourf(h, levels=[10, 30, 50], colors=['#808080', '#A0A0A0', '#C0C0C0'], extend='both') cs.cmap.set_over('red') cs.cmap.set_under('blue') cs.changed()
xunits (registered units, optional) – Override axis units by specifying an instance of a
matplotlib.units.ConversionInterface.yunits (registered units, optional) – Override axis units by specifying an instance of a
matplotlib.units.ConversionInterface.antialiased (bool, optional) – Enable antialiasing, overriding the defaults. For filled contours, the default is False. For line contours, it is taken from
rcParams[“lines.antialiased”](default:True).nchunk (int >= 0, optional) – If 0, no subdivision of the domain. Specify a positive integer to divide the domain into subdomains of nchunk by nchunk quads. Chunking reduces the maximum length of polygons generated by the contouring algorithm which reduces the rendering workload passed on to the backend and also requires slightly less RAM. It can however introduce rendering artifacts at chunk boundaries depending on the backend, the antialiased flag and value of alpha.
linewidths (float or array-like, default:
rcParams[“contour.linewidth”](default:None)) –Only applies to .contour.
The line width of the contour lines.
If a number, all levels will be plotted with this linewidth.
If a sequence, the levels in ascending order will be plotted with the linewidths in the order specified.
If None, this falls back to
rcParams[“lines.linewidth”](default:1.5).linestyles ({None, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’}, optional) –
Only applies to .contour.
If linestyles is None, the default is ‘solid’ unless the lines are monochrome. In that case, negative contours will instead take their linestyle from the negative_linestyles argument.
linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary.
negative_linestyles ({None, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’}, optional) –
Only applies to .contour.
If linestyles is None and the lines are monochrome, this argument specifies the line style for negative contours.
If negative_linestyles is None, the default is taken from
rcParams[“contour.negative_linestyle”](default:'dashed').negative_linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary.
hatches (list[str], optional) –
Only applies to .contourf.
A list of cross hatch patterns to use on the filled areas. If None, no hatching will be added to the contour.
algorithm ({'mpl2005', 'mpl2014', 'serial', 'threaded'}, optional) –
Which contouring algorithm to use to calculate the contour lines and polygons. The algorithms are implemented in ContourPy, consult the ContourPy documentation for further information.
The default is taken from
rcParams[“contour.algorithm”](default:'mpl2014').clip_path (~matplotlib.patches.Patch or .Path or .TransformedPath) –
Set the clip path. See ~matplotlib.artist.Artist.set_clip_path.
Added in version 3.8.
data (indexable object, optional) – If given, all parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata.
- Return type:
~.contour.QuadContourSet
Notes
Note
This is the pyplot wrapper for .axes.Axes.contourf.
.contourf differs from the MATLAB version in that it does not draw the polygon edges. To draw edges, add line contours with calls to .contour.
.contourf fills intervals that are closed at the top; that is, for boundaries z1 and z2, the filled region is:
z1 < Z <= z2
except for the lowest interval, which is closed on both sides (i.e. it includes the lowest value).
.contour and .contourf use a marching squares algorithm to compute contour locations. More information can be found in ContourPy documentation.
- scitex.plt.colorbar(mappable=None, cax=None, ax=None, **kwargs)[source]
Add a colorbar to a plot.
- Parameters:
mappable (
_ScalarMappable|ColorizingArtist|None) –The matplotlib.cm.ScalarMappable (i.e., .AxesImage, .ContourSet, etc.) described by this colorbar. This argument is mandatory for the .Figure.colorbar method but optional for the .pyplot.colorbar function, which sets the default to the current image.
Note that one can create a .ScalarMappable “on-the-fly” to generate colorbars not attached to a previously drawn artist, e.g.
fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)
cax (~matplotlib.axes.Axes, optional) – Axes into which the colorbar will be drawn. If None, then a new Axes is created and the space for it will be stolen from the Axes(s) specified in ax.
ax (~matplotlib.axes.Axes or iterable or numpy.ndarray of Axes, optional) –
The one or more parent Axes from which space for a new colorbar Axes will be stolen. This parameter is only used if cax is not set.
Defaults to the Axes that contains the mappable used to create the colorbar.
use_gridspec (bool, optional) – If cax is
None, a new cax is created as an instance of Axes. If ax is positioned with a subplotspec and use_gridspec isTrue, then cax is also positioned with a subplotspec.location (None or {'left', 'right', 'top', 'bottom'}) – The location, relative to the parent Axes, where the colorbar Axes is created. It also determines the orientation of the colorbar (colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal). If None, the location will come from the orientation if it is set (vertical colorbars on the right, horizontal ones at the bottom), or default to ‘right’ if orientation is unset.
orientation (None or {'vertical', 'horizontal'}) – The orientation of the colorbar. It is preferable to set the location of the colorbar, as that also determines the orientation; passing incompatible values for location and orientation raises an exception.
fraction (float, default: 0.15) – Fraction of original Axes to use for colorbar.
shrink (float, default: 1.0) – Fraction by which to multiply the size of the colorbar.
aspect (float, default: 20) – Ratio of long to short dimensions.
pad (float, default: 0.05 if vertical, 0.15 if horizontal) – Fraction of original Axes between colorbar and new image Axes.
anchor ((float, float), optional) – The anchor point of the colorbar Axes. Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal.
panchor ((float, float), or False, optional) – The anchor point of the colorbar parent Axes. If False, the parent axes’ anchor will be unchanged. Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal.
extend ({'neither', 'both', 'min', 'max'}) – Make pointed end(s) for out-of-range values (unless ‘neither’). These are set for a given colormap using the colormap set_under and set_over methods.
extendfrac ({None, ‘auto’, length, lengths}) –
If set to None, both the minimum and maximum triangular colorbar extensions will have a length of 5% of the interior colorbar length (this is the default setting).
If set to ‘auto’, makes the triangular colorbar extensions the same lengths as the interior boxes (when spacing is set to ‘uniform’) or the same lengths as the respective adjacent interior boxes (when spacing is set to ‘proportional’).
If a scalar, indicates the length of both the minimum and maximum triangular colorbar extensions as a fraction of the interior colorbar length. A two-element sequence of fractions may also be given, indicating the lengths of the minimum and maximum colorbar extensions respectively as a fraction of the interior colorbar length.
extendrect (bool) – If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular.
ticks (None or list of ticks or Locator) – If None, ticks are determined automatically from the input.
format (None or str or Formatter) – If None, ~.ticker.ScalarFormatter is used. Format strings, e.g.,
"%4.2e"or"{x:.2e}", are supported. An alternative ~.ticker.Formatter may be given instead.drawedges (bool) – Whether to draw lines at color boundaries.
label (str) – The label on the colorbar’s long axis.
boundaries (None or a sequence) – If unset, the colormap will be displayed on a 0-1 scale. If sequences, values must have a length 1 less than boundaries. For each region delimited by adjacent entries in boundaries, the color mapped to the corresponding value in values will be used. The size of each region is determined by the spacing parameter. Normally only useful for indexed colors (i.e.
norm=NoNorm()) or other unusual circumstances.values (None or a sequence) – If unset, the colormap will be displayed on a 0-1 scale. If sequences, values must have a length 1 less than boundaries. For each region delimited by adjacent entries in boundaries, the color mapped to the corresponding value in values will be used. The size of each region is determined by the spacing parameter. Normally only useful for indexed colors (i.e.
norm=NoNorm()) or other unusual circumstances.spacing ({'uniform', 'proportional'}) – For discrete colorbars (.BoundaryNorm or contours), ‘uniform’ gives each color the same space; ‘proportional’ makes the space proportional to the data interval.
- Returns:
colorbar
- Return type:
~matplotlib.colorbar.Colorbar
Notes
Note
This is the pyplot wrapper for .Figure.colorbar.
If mappable is a ~.contour.ContourSet, its extend kwarg is included automatically.
The shrink kwarg provides a simple way to scale the colorbar with respect to the Axes. Note that if cax is specified, it determines the size of the colorbar, and shrink and aspect are ignored.
For more precise control, you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn. In this case, do not use any of the Axes properties kwargs.
It is known that some vector graphics viewers (svg and pdf) render white gaps between segments of the colorbar. This is due to bugs in the viewers, not Matplotlib. As a workaround, the colorbar can be rendered with overlapping segments:
cbar = colorbar() cbar.solids.set_edgecolor("face") draw()
However, this has negative consequences in other circumstances, e.g. with semi-transparent images (alpha < 1) and colorbar extensions; therefore, this workaround is not used by default (see issue #1188).
- scitex.plt.axhline(y=0, xmin=0, xmax=1, **kwargs)[source]
Add a horizontal line spanning the whole or fraction of the Axes.
Note: If you want to set x-limits in data coordinates, use ~.Axes.hlines instead.
- Parameters:
y (float, default: 0) – y position in data coordinates.
xmin (float, default: 0) – The start x-position in axes coordinates. 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) – The end x-position in axes coordinates. 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, except for ‘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 and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color 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: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: color or 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] mouseover: bool path_effects: list of .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: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float
- Returns:
A .Line2D specified via two points
(xmin, y),(xmax, y). Its transform is set such that x is in axes coordinates and y is in data coordinates.This is still a generic line and the horizontal character is only realized through using identical y values for both points. Thus, if you want to change the y value later, you have to provide two values
line.set_ydata([3, 3]).- Return type:
~matplotlib.lines.Line2D
See also
hlinesAdd horizontal lines in data coordinates.
axhspanAdd a horizontal span (rectangle) across the axis.
axlineAdd a line with an arbitrary slope.
Notes
Note
This is the pyplot wrapper for .axes.Axes.axhline.
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)
- scitex.plt.axvline(x=0, ymin=0, ymax=1, **kwargs)[source]
Add a vertical line spanning the whole or fraction of the Axes.
Note: If you want to set y-limits in data coordinates, use ~.Axes.vlines instead.
- Parameters:
x (float, default: 0) – x position in data coordinates.
ymin (float, default: 0) – The start y-position in axes coordinates. Should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot.
ymax (float, default: 1) – The end y-position in axes coordinates. 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, except for ‘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 and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color 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: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: color or 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] mouseover: bool path_effects: list of .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: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float
- Returns:
A .Line2D specified via two points
(x, ymin),(x, ymax). Its transform is set such that x is in data coordinates and y is in axes coordinates.This is still a generic line and the vertical character is only realized through using identical x values for both points. Thus, if you want to change the x value later, you have to provide two values
line.set_xdata([3, 3]).- Return type:
~matplotlib.lines.Line2D
See also
vlinesAdd vertical lines in data coordinates.
axvspanAdd a vertical span (rectangle) across the axis.
axlineAdd a line with an arbitrary slope.
Notes
Note
This is the pyplot wrapper for .axes.Axes.axvline.
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)
- scitex.plt.text(x, y, s, fontdict=None, **kwargs)[source]
Add text to the Axes.
Add the text s to the Axes at location x, y in data coordinates, with a default
horizontalalignmenton theleftandverticalalignmentat thebaseline. See /gallery/text_labels_and_annotations/text_alignment.- 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) –
Discouraged
The use of fontdict is discouraged. Parameters should be passed as individual keyword arguments or using dictionary-unpacking
text(..., **fontdict).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 and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased: bool backgroundcolor: color bbox: dict with properties for .patches.FancyBboxPatch clip_box: unknown clip_on: unknown clip_path: unknown color or c: color figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fontfamily or family or fontname: {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: {‘left’, ‘center’, ‘right’} in_layout: bool label: object linespacing: float (multiple of font size) math_fontfamily: str mouseover: bool multialignment or ma: {‘left’, ‘right’, ‘center’} parse_math: bool path_effects: list of .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: ~matplotlib.transforms.Transform transform_rotates_text: bool url: str usetex: bool, default:
rcParams[“text.usetex”](default:False) verticalalignment or va: {‘baseline’, ‘bottom’, ‘center’, ‘center_baseline’, ‘top’} visible: bool wrap: bool x: float y: float zorder: float
- Returns:
The created .Text instance.
- Return type:
.Text
Notes
Note
This is the pyplot wrapper for .axes.Axes.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))
- scitex.plt.annotate(text, xy, xytext=None, xycoords='data', textcoords=None, arrowprops=None, annotation_clip=None, **kwargs)[source]
Annotate the point xy with text text.
In the simplest form, the text is placed at xy.
Optionally, the text can be displayed in another position xytext. An arrow pointing from the text to the annotated point xy can then be added by defining arrowprops.
- Parameters:
text (str) – The text of the annotation.
xy ((float, float)) – The point (x, y) to annotate. The coordinate system is determined by xycoords.
xytext ((float, float), default: xy) – The position (x, y) to place the text at. The coordinate system is determined by textcoords.
xycoords (single or two-tuple of str or .Artist or .Transform or callable, default: ‘data’) –
The coordinate system that xy is given in. The following types of values are supported:
One of the following strings:
Value
Description
’figure points’
Points from the lower left of the figure
’figure pixels’
Pixels from the lower left of the figure
’figure fraction’
Fraction of figure from lower left
’subfigure points’
Points from the lower left of the subfigure
’subfigure pixels’
Pixels from the lower left of the subfigure
’subfigure fraction’
Fraction of subfigure from lower left
’axes points’
Points from lower left corner of the Axes
’axes pixels’
Pixels from lower left corner of the Axes
’axes fraction’
Fraction of Axes from lower left
’data’
Use the coordinate system of the object being annotated (default)
’polar’
(theta, r) if not native ‘data’ coordinates
Note that ‘subfigure pixels’ and ‘figure pixels’ are the same for the parent figure, so users who want code that is usable in a subfigure can use ‘subfigure pixels’.
An .Artist: xy is interpreted as a fraction of the artist’s ~matplotlib.transforms.Bbox. E.g. (0, 0) would be the lower left corner of the bounding box and (0.5, 1) would be the center top of the bounding box.
A .Transform to transform xy to screen coordinates.
A function with one of the following signatures:
def transform(renderer) -> Bbox def transform(renderer) -> Transform
where renderer is a .RendererBase subclass.
The result of the function is interpreted like the .Artist and .Transform cases above.
A tuple (xcoords, ycoords) specifying separate coordinate systems for x and y. xcoords and ycoords must each be of one of the above described types.
See Advanced annotation for more details.
textcoords (single or two-tuple of str or .Artist or .Transform or callable, default: value of xycoords) –
The coordinate system that xytext is given in.
All xycoords values are valid as well as the following strings:
Value
Description
’offset points’
Offset, in points, from the xy value
’offset pixels’
Offset, in pixels, from the xy value
’offset fontsize’
Offset, relative to fontsize, from the xy value
arrowprops (dict, optional) –
The properties used to draw a .FancyArrowPatch arrow between the positions xy and xytext. Defaults to None, i.e. no arrow is drawn.
For historical reasons there are two different ways to specify arrows, “simple” and “fancy”:
Simple arrow:
If arrowprops does not contain the key ‘arrowstyle’ the allowed keys are:
Key
Description
width
The width of the arrow in points
headwidth
The width of the base of the arrow head in points
headlength
The length of the arrow head in points
shrink
Fraction of total length to shrink from both ends
?
Any .FancyArrowPatch property
The arrow is attached to the edge of the text box, the exact position (corners or centers) depending on where it’s pointing to.
Fancy arrow:
This is used if ‘arrowstyle’ is provided in the arrowprops.
Valid keys are the following .FancyArrowPatch parameters:
Key
Description
arrowstyle
The arrow style
connectionstyle
The connection style
relpos
See below; default is (0.5, 0.5)
patchA
Default is bounding box of the text
patchB
Default is None
shrinkA
In points. Default is 2 points
shrinkB
In points. Default is 2 points
mutation_scale
Default is text size (in points)
mutation_aspect
Default is 1
?
Any .FancyArrowPatch property
The exact starting point position of the arrow is defined by relpos. It’s a tuple of relative coordinates of the text box, where (0, 0) is the lower left corner and (1, 1) is the upper right corner. Values <0 and >1 are supported and specify points outside the text box. By default (0.5, 0.5), so the starting point is centered in the text box.
annotation_clip (bool or None, default: None) –
Whether to clip (i.e. not draw) the annotation when the annotation point xy is outside the Axes area.
If True, the annotation will be clipped when xy is outside the Axes.
If False, the annotation will always be drawn.
If None, the annotation will be clipped when xy is outside the Axes and xycoords is ‘data’.
**kwargs – Additional kwargs are passed to .Text.
- Return type:
.Annotation
See also
Notes
Note
This is the pyplot wrapper for .axes.Axes.annotate.
- scitex.plt.fill_between(x, y1, y2=0, where=None, interpolate=False, step=None, *, data=None, **kwargs)[source]
Fill the area between two horizontal curves.
The curves are defined by the points (x, y1) and (x, y2). This creates one or multiple polygons describing the filled area.
You may exclude some horizontal sections from filling using where.
By default, the edges connect the given points directly. Use step if the filling should be a step function, i.e. constant in between x.
- Parameters:
x (array-like) – The x coordinates of the nodes defining the curves.
y1 (array-like or float) – The y coordinates of the nodes defining the first curve.
y2 (array-like or float, default: 0) – The y coordinates of the nodes defining the second curve.
where (array-like of bool, optional) – Define where to exclude some horizontal regions from being filled. The filled regions are defined by the coordinates
x[where]. More precisely, fill betweenx[i]andx[i+1]ifwhere[i] and where[i+1]. Note that this definition implies that an isolated True value between two False values in where will not result in filling. Both sides of the True position remain unfilled due to the adjacent False values.interpolate (bool, default: False) –
This option is only relevant if where is used and the two curves are crossing each other.
Semantically, where is often used for y1 > y2 or similar. By default, the nodes of the polygon defining the filled region will only be placed at the positions in the x array. Such a polygon cannot describe the above semantics close to the intersection. The x-sections containing the intersection are simply clipped.
Setting interpolate to True will calculate the actual intersection point and extend the filled region up to this point.
step ({'pre', 'post', 'mid'}, optional) –
Define step if the filling should be a step function, i.e. constant in between x. The value determines where the step will occur:
’pre’: The y value is continued constantly to the left from every x position, i.e. the interval
(x[i-1], x[i]]has the valuey[i].’post’: The y value is continued constantly to the right from every x position, i.e. the interval
[x[i], x[i+1])has the valuey[i].’mid’: Steps occur half-way between the x positions.
data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x, y1, y2, where
**kwargs –
All other keyword arguments are passed on to .FillBetweenPolyCollection. They control the .Polygon 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 and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased or aa or antialiaseds: bool or list of bools array: array-like or None capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clim: (vmin: float, vmax: float) clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: color or list of RGBA tuples data: array-like edgecolor or ec or edgecolors: color or list of color or ‘face’ facecolor or facecolors or fc: color or list of color figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown 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 mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .AbstractPathEffect paths: list of array-like picker: None or bool or float or callable pickradius: float rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str urls: list of str or None verts: list of array-like verts_and_codes: unknown visible: bool zorder: float
- Returns:
A .FillBetweenPolyCollection containing the plotted polygons.
- Return type:
.FillBetweenPolyCollection
See also
fill_betweenFill between two sets of y-values.
fill_betweenxFill between two sets of x-values.
Notes
Note
This is the pyplot wrapper for .axes.Axes.fill_between.
- scitex.plt.errorbar(x, y, yerr=None, xerr=None, fmt='', ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, *, data=None, **kwargs)[source]
Plot y versus x as lines and/or markers with attached errorbars.
x, y define the data locations, xerr, yerr define the errorbar sizes. By default, this draws the data markers/lines as well as the errorbars. Use fmt=’none’ to draw errorbars without any data markers.
Added in version 3.7: Caps and error lines are drawn in polar coordinates on polar plots.
- Parameters:
x (float or array-like) – The data positions.
y (float or array-like) – The data positions.
xerr (float or array-like, shape(N,) or shape(2, N), optional) –
The errorbar sizes:
scalar: Symmetric +/- values for all data points.
shape(N,): Symmetric +/-values for each data point.
shape(2, N): Separate - and + values for each bar. First row contains the lower errors, the second row contains the upper errors.
None: No errorbar.
All values must be >= 0.
See /gallery/statistics/errorbar_features for an example on the usage of
xerrandyerr.yerr (float or array-like, shape(N,) or shape(2, N), optional) –
The errorbar sizes:
scalar: Symmetric +/- values for all data points.
shape(N,): Symmetric +/-values for each data point.
shape(2, N): Separate - and + values for each bar. First row contains the lower errors, the second row contains the upper errors.
None: No errorbar.
All values must be >= 0.
See /gallery/statistics/errorbar_features for an example on the usage of
xerrandyerr.fmt (str, default: '') –
The format for the data points / data lines. See .plot for details.
Use ‘none’ (case-insensitive) to plot errorbars without any data markers.
ecolor (color, default: None) – The color of the errorbar lines. If None, use the color of the line connecting the markers.
elinewidth (float, default: None) – The linewidth of the errorbar lines. If None, the linewidth of the current style is used.
capsize (float, default:
rcParams[“errorbar.capsize”](default:0.0)) – The length of the error bar caps in points.capthick (float, default: None) – An alias to the keyword argument markeredgewidth (a.k.a. mew). This setting is a more sensible name for the property that controls the thickness of the error bar cap in points. For backwards compatibility, if mew or markeredgewidth are given, then they will over-ride capthick. This may change in future releases.
barsabove (bool, default: False) – If True, will plot the errorbars above the plot symbols. Default is below.
lolims (bool or array-like, default: False) – These arguments can be used to indicate that a value gives only upper/lower limits. In that case a caret symbol is used to indicate this. lims-arguments may be scalars, or array-likes of the same length as xerr and yerr. To use limits with inverted axes, ~.Axes.set_xlim or ~.Axes.set_ylim must be called before
errorbar(). Note the tricky parameter names: setting e.g. lolims to True means that the y-value is a lower limit of the True value, so, only an upward-pointing arrow will be drawn!uplims (bool or array-like, default: False) – These arguments can be used to indicate that a value gives only upper/lower limits. In that case a caret symbol is used to indicate this. lims-arguments may be scalars, or array-likes of the same length as xerr and yerr. To use limits with inverted axes, ~.Axes.set_xlim or ~.Axes.set_ylim must be called before
errorbar(). Note the tricky parameter names: setting e.g. lolims to True means that the y-value is a lower limit of the True value, so, only an upward-pointing arrow will be drawn!xlolims (bool or array-like, default: False) – These arguments can be used to indicate that a value gives only upper/lower limits. In that case a caret symbol is used to indicate this. lims-arguments may be scalars, or array-likes of the same length as xerr and yerr. To use limits with inverted axes, ~.Axes.set_xlim or ~.Axes.set_ylim must be called before
errorbar(). Note the tricky parameter names: setting e.g. lolims to True means that the y-value is a lower limit of the True value, so, only an upward-pointing arrow will be drawn!xuplims (bool or array-like, default: False) – These arguments can be used to indicate that a value gives only upper/lower limits. In that case a caret symbol is used to indicate this. lims-arguments may be scalars, or array-likes of the same length as xerr and yerr. To use limits with inverted axes, ~.Axes.set_xlim or ~.Axes.set_ylim must be called before
errorbar(). Note the tricky parameter names: setting e.g. lolims to True means that the y-value is a lower limit of the True value, so, only an upward-pointing arrow will be drawn!errorevery (int or (int, int), default: 1) – draws error bars on a subset of the data. errorevery =N draws error bars on the points (x[::N], y[::N]). errorevery =(start, N) draws error bars on the points (x[start::N], y[start::N]). e.g. errorevery=(6, 3) adds error bars to the data at (x[6], x[9], x[12], x[15], …). Used to avoid overlapping error bars when two series share x-axis values.
data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x, y, xerr, yerr
**kwargs –
All other keyword arguments are passed on to the ~.Axes.plot call drawing the markers. For example, this code makes big red squares with thick green edges:
x, y, yerr = rand(3, 10) errorbar(x, y, yerr, marker='s', mfc='red', mec='green', ms=20, mew=4)
where mfc, mec, ms and mew are aliases for the longer property names, markerfacecolor, markeredgecolor, markersize and markeredgewidth.
Valid kwargs for the marker properties are:
dashes
dash_capstyle
dash_joinstyle
drawstyle
fillstyle
linestyle
marker
markeredgecolor
markeredgewidth
markerfacecolor
markerfacecoloralt
markersize
markevery
solid_capstyle
solid_joinstyle
Refer to the corresponding .Line2D property for more details:
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 and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color 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: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: color or 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] mouseover: bool path_effects: list of .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: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float
- Returns:
The container contains:
data_line : A ~matplotlib.lines.Line2D instance of x, y plot markers and/or line.
caplines : A tuple of ~matplotlib.lines.Line2D instances of the error bar caps.
barlinecols : A tuple of .LineCollection with the horizontal and vertical error ranges.
- Return type:
.ErrorbarContainer
Notes
Note
This is the pyplot wrapper for .axes.Axes.errorbar.
- scitex.plt.boxplot(x, notch=None, sym=None, vert=None, orientation='vertical', whis=None, positions=None, widths=None, patch_artist=None, bootstrap=None, usermedians=None, conf_intervals=None, meanline=None, showmeans=None, showcaps=None, showbox=None, showfliers=None, boxprops=None, tick_labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None, manage_ticks=True, autorange=False, zorder=None, capwidths=None, label=None, *, data=None)[source]
Draw a box and whisker plot.
The box extends from the first quartile (Q1) to the third quartile (Q3) of the data, with a line at the median. The whiskers extend from the box to the farthest data point lying within 1.5x the inter-quartile range (IQR) from the box. Flier points are those past the end of the whiskers. See https://en.wikipedia.org/wiki/Box_plot for reference.
Q1-1.5IQR Q1 median Q3 Q3+1.5IQR |-----:-----| o |--------| : |--------| o o |-----:-----| flier <-----------> fliers IQR- Parameters:
x (Array or a sequence of vectors.) – The input data. If a 2D array, a boxplot is drawn for each column in x. If a sequence of 1D arrays, a boxplot is drawn for each array in x.
notch (bool, default:
rcParams[“boxplot.notch”](default:False)) –Whether to draw a notched boxplot (True), or a rectangular boxplot (False). The notches represent the confidence interval (CI) around the median. The documentation for bootstrap describes how the locations of the notches are computed by default, but their locations may also be overridden by setting the conf_intervals parameter.
Note
In cases where the values of the CI are less than the lower quartile or greater than the upper quartile, the notches will extend beyond the box, giving it a distinctive “flipped” appearance. This is expected behavior and consistent with other statistical visualization packages.
sym (str, optional) – The default symbol for flier points. An empty string (‘’) hides the fliers. If None, then the fliers default to ‘b+’. More control is provided by the flierprops parameter.
vert (bool, optional) –
Deprecated since version 3.11: Use orientation instead.
This is a pending deprecation for 3.10, with full deprecation in 3.11 and removal in 3.13. If this is given during the deprecation period, it overrides the orientation parameter.
If True, plots the boxes vertically. If False, plots the boxes horizontally.
orientation ({'vertical', 'horizontal'}, default: 'vertical') –
If ‘horizontal’, plots the boxes horizontally. Otherwise, plots the boxes vertically.
Added in version 3.10.
whis (float or (float, float), default: 1.5) –
The position of the whiskers.
If a float, the lower whisker is at the lowest datum above
Q1 - whis*(Q3-Q1), and the upper whisker at the highest datum belowQ3 + whis*(Q3-Q1), where Q1 and Q3 are the first and third quartiles. The default value ofwhis = 1.5corresponds to Tukey’s original definition of boxplots.If a pair of floats, they indicate the percentiles at which to draw the whiskers (e.g., (5, 95)). In particular, setting this to (0, 100) results in whiskers covering the whole range of the data.
In the edge case where
Q1 == Q3, whis is automatically set to (0, 100) (cover the whole range of the data) if autorange is True.Beyond the whiskers, data are considered outliers and are plotted as individual points.
bootstrap (int, optional) – Specifies whether to bootstrap the confidence intervals around the median for notched boxplots. If bootstrap is None, no bootstrapping is performed, and notches are calculated using a Gaussian-based asymptotic approximation (see McGill, R., Tukey, J.W., and Larsen, W.A., 1978, and Kendall and Stuart, 1967). Otherwise, bootstrap specifies the number of times to bootstrap the median to determine its 95% confidence intervals. Values between 1000 and 10000 are recommended.
usermedians (1D array-like, optional) – A 1D array-like of length
len(x). Each entry that is not None forces the value of the median for the corresponding dataset. For entries that are None, the medians are computed by Matplotlib as normal.conf_intervals (array-like, optional) – A 2D array-like of shape
(len(x), 2). Each entry that is not None forces the location of the corresponding notch (which is only drawn if notch is True). For entries that are None, the notches are computed by the method specified by the other parameters (e.g., bootstrap).positions (array-like, optional) – The positions of the boxes. The ticks and limits are automatically set to match the positions. Defaults to
range(1, N+1)where N is the number of boxes to be drawn.widths (float or array-like) – The widths of the boxes. The default is 0.5, or
0.15*(distance between extreme positions), if that is smaller.patch_artist (bool, default:
rcParams[“boxplot.patchartist”](default:False)) – If False produces boxes with the Line2D artist. Otherwise, boxes are drawn with Patch artists.tick_labels (list of str, optional) –
The tick labels of each boxplot. Ticks are always placed at the box positions. If tick_labels is given, the ticks are labelled accordingly. Otherwise, they keep their numeric values.
Changed in version 3.9: Renamed from labels, which is deprecated since 3.9 and will be removed in 3.11.
manage_ticks (bool, default: True) – If True, the tick locations and labels will be adjusted to match the boxplot positions.
autorange (bool, default: False) – When True and the data are distributed such that the 25th and 75th percentiles are equal, whis is set to (0, 100) such that the whisker ends are at the minimum and maximum of the data.
meanline (bool, default:
rcParams[“boxplot.meanline”](default:False)) – If True (and showmeans is True), will try to render the mean as a line spanning the full width of the box according to meanprops (see below). Not recommended if shownotches is also True. Otherwise, means will be shown as points.zorder (float, default:
Line2D.zorder = 2) – The zorder of the boxplot.showcaps (bool, default:
rcParams[“boxplot.showcaps”](default:True)) – Show the caps on the ends of whiskers.showbox (bool, default:
rcParams[“boxplot.showbox”](default:True)) – Show the central box.showfliers (bool, default:
rcParams[“boxplot.showfliers”](default:True)) – Show the outliers beyond the caps.showmeans (bool, default:
rcParams[“boxplot.showmeans”](default:False)) – Show the arithmetic means.capprops (dict, default: None) – The style of the caps.
capwidths (float or array, default: None) – The widths of the caps.
boxprops (dict, default: None) – The style of the box.
whiskerprops (dict, default: None) – The style of the whiskers.
flierprops (dict, default: None) – The style of the fliers.
medianprops (dict, default: None) – The style of the median.
meanprops (dict, default: None) – The style of the mean.
label (str or list of str, optional) –
Legend labels. Use a single string when all boxes have the same style and you only want a single legend entry for them. Use a list of strings to label all boxes individually. To be distinguishable, the boxes should be styled individually, which is currently only possible by modifying the returned artists, see e.g. /gallery/statistics/boxplot_demo.
In the case of a single string, the legend entry will technically be associated with the first box only. By default, the legend will show the median line (
result["medians"]); if patch_artist is True, the legend will show the box .Patch artists (result["boxes"]) instead.Added in version 3.9.
data (indexable object, optional) – If given, all parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata.
- Returns:
A dictionary mapping each component of the boxplot to a list of the .Line2D instances created. That dictionary has the following keys (assuming vertical boxplots):
boxes: the main body of the boxplot showing the quartiles and the median’s confidence intervals if enabled.medians: horizontal lines at the median of each box.whiskers: the vertical lines extending to the most extreme, non-outlier data points.caps: the horizontal lines at the ends of the whiskers.fliers: points representing data that extend beyond the whiskers (fliers).means: points or lines representing the means.
- Return type:
See also
Axes.bxpDraw a boxplot from pre-computed statistics.
violinplotDraw an estimate of the probability density function.
Notes
Note
This is the pyplot wrapper for .axes.Axes.boxplot.
- scitex.plt.violinplot(dataset, positions=None, vert=None, orientation='vertical', widths=0.5, showmeans=False, showextrema=True, showmedians=False, quantiles=None, points=100, bw_method=None, side='both', *, data=None)[source]
Make a violin plot.
Make a violin plot for each column of dataset or each vector in sequence dataset. Each filled area extends to represent the entire data range, with optional lines at the mean, the median, the minimum, the maximum, and user-specified quantiles.
- Parameters:
dataset (Array or a sequence of vectors.) – The input data.
positions (array-like, default: [1, 2, ..., n]) – The positions of the violins; i.e. coordinates on the x-axis for vertical violins (or y-axis for horizontal violins).
vert (bool, optional) –
Deprecated since version 3.10: Use orientation instead.
If this is given during the deprecation period, it overrides the orientation parameter.
If True, plots the violins vertically. If False, plots the violins horizontally.
orientation ({'vertical', 'horizontal'}, default: 'vertical') –
If ‘horizontal’, plots the violins horizontally. Otherwise, plots the violins vertically.
Added in version 3.10.
widths (float or array-like, default: 0.5) – The maximum width of each violin in units of the positions axis. The default is 0.5, which is half the available space when using default positions.
showmeans (bool, default: False) – Whether to show the mean with a line.
showextrema (bool, default: True) – Whether to show extrema with a line.
showmedians (bool, default: False) – Whether to show the median with a line.
quantiles (array-like, default: None) – If not None, set a list of floats in interval [0, 1] for each violin, which stands for the quantiles that will be rendered for that violin.
points (int, default: 100) – The number of points to evaluate each of the gaussian kernel density estimations at.
bw_method ({'scott', 'silverman'} or float or callable, default: 'scott') – The method used to calculate the estimator bandwidth. If a float, this will be used directly as kde.factor. If a callable, it should take a matplotlib.mlab.GaussianKDE instance as its only parameter and return a float.
side ({'both', 'low', 'high'}, default: 'both') – ‘both’ plots standard violins. ‘low’/’high’ only plots the side below/above the positions value.
data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:dataset
- Returns:
A dictionary mapping each component of the violinplot to a list of the corresponding collection instances created. The dictionary has the following keys:
bodies: A list of the ~.collections.PolyCollection instances containing the filled area of each violin.cmeans: A ~.collections.LineCollection instance that marks the mean values of each of the violin’s distribution.cmins: A ~.collections.LineCollection instance that marks the bottom of each violin’s distribution.cmaxes: A ~.collections.LineCollection instance that marks the top of each violin’s distribution.cbars: A ~.collections.LineCollection instance that marks the centers of each violin’s distribution.cmedians: A ~.collections.LineCollection instance that marks the median values of each of the violin’s distribution.cquantiles: A ~.collections.LineCollection instance created to identify the quantile values of each of the violin’s distribution.
- Return type:
See also
Axes.violinDraw a violin from pre-computed statistics.
boxplotDraw a box and whisker plot.
Notes
Note
This is the pyplot wrapper for .axes.Axes.violinplot.
- scitex.plt.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=0, radius=1, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, rotatelabels=False, *, normalize=True, hatch=None, data=None)[source]
Plot a pie chart.
Make a pie chart of array x. The fractional area of each wedge is given by
x/sum(x).The wedges are plotted counterclockwise, by default starting from the x-axis.
- Parameters:
x (1D array-like) – The wedge sizes.
explode (array-like, default: None) – If not None, is a
len(x)array which specifies the fraction of the radius with which to offset each wedge.labels (list, default: None) – A sequence of strings providing the labels for each wedge
colors (color or list of color, default: None) – A sequence of colors through which the pie chart will cycle. If None, will use the colors in the currently active cycle.
hatch (str or list, default: None) –
Hatching pattern applied to all pie wedges or sequence of patterns through which the chart will cycle. For a list of valid patterns, see /gallery/shapes_and_collections/hatch_style_reference.
Added in version 3.7.
autopct (None or str or callable, default: None) – If not None, autopct is a string or function used to label the wedges with their numeric value. The label will be placed inside the wedge. If autopct is a format string, the label will be
fmt % pct. If autopct is a function, then it will be called.pctdistance (float, default: 0.6) – The relative distance along the radius at which the text generated by autopct is drawn. To draw the text outside the pie, set pctdistance > 1. This parameter is ignored if autopct is
None.labeldistance (float or None, default: 1.1) – The relative distance along the radius at which the labels are drawn. To draw the labels inside the pie, set labeldistance < 1. If set to
None, labels are not drawn but are still stored for use in .legend.shadow (bool or dict, default: False) –
If bool, whether to draw a shadow beneath the pie. If dict, draw a shadow passing the properties in the dict to .Shadow.
Added in version 3.8: shadow can be a dict.
startangle (float, default: 0 degrees) – The angle by which the start of the pie is rotated, counterclockwise from the x-axis.
radius (float, default: 1) – The radius of the pie.
counterclock (bool, default: True) – Specify fractions direction, clockwise or counterclockwise.
wedgeprops (dict, default: None) – Dict of arguments passed to each .patches.Wedge of the pie. For example,
wedgeprops = {'linewidth': 3}sets the width of the wedge border lines equal to 3. By default,clip_on=False. When there is a conflict between these properties and other keywords, properties passed to wedgeprops take precedence.textprops (dict, default: None) – Dict of arguments to pass to the text objects.
center ((float, float), default: (0, 0)) – The coordinates of the center of the chart.
frame (bool, default: False) – Plot Axes frame with the chart if true.
rotatelabels (bool, default: False) – Rotate each label to the angle of the corresponding slice if true.
normalize (bool, default: True) – When True, always make a full pie by normalizing x so that
sum(x) == 1. False makes a partial pie ifsum(x) <= 1and raises a ValueError forsum(x) > 1.data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x, explode, labels, colors
- Return type:
tuple[list[Wedge],list[Text]] |tuple[list[Wedge],list[Text],list[Text]]- Returns:
patches (list) – A sequence of matplotlib.patches.Wedge instances
texts (list) – A list of the label .Text instances.
autotexts (list) – A list of .Text instances for the numeric labels. This will only be returned if the parameter autopct is not None.
Notes
Note
This is the pyplot wrapper for .axes.Axes.pie.
The pie chart will probably look best if the figure and Axes are square, or the Axes aspect is equal. This method sets the aspect ratio of the axis to “equal”. The Axes aspect ratio can be controlled with .Axes.set_aspect.
- scitex.plt.stem(*args, linefmt=None, markerfmt=None, basefmt=None, bottom=0, label=None, orientation='vertical', data=None)[source]
Create a stem plot.
A stem plot draws lines perpendicular to a baseline at each location locs from the baseline to heads, and places a marker there. For vertical stem plots (the default), the locs are x positions, and the heads are y values. For horizontal stem plots, the locs are y positions, and the heads are x values.
Call signature:
stem([locs,] heads, linefmt=None, markerfmt=None, basefmt=None)
The locs-positions are optional. linefmt may be provided as positional, but all other formats must be provided as keyword arguments.
- Parameters:
locs (array-like, default: (0, 1, ..., len(heads) - 1)) – For vertical stem plots, the x-positions of the stems. For horizontal stem plots, the y-positions of the stems.
heads (array-like) – For vertical stem plots, the y-values of the stem heads. For horizontal stem plots, the x-values of the stem heads.
linefmt (str, optional) –
A string defining the color and/or linestyle of the vertical lines:
Character
Line Style
'-'solid line
'--'dashed line
'-.'dash-dot line
':'dotted line
Default: ‘C0-’, i.e. solid line with the first color of the color cycle.
Note: Markers specified through this parameter (e.g. ‘x’) will be silently ignored. Instead, markers should be specified using markerfmt.
markerfmt (str, optional) – A string defining the color and/or shape of the markers at the stem heads. If the marker is not given, use the marker ‘o’, i.e. filled circles. If the color is not given, use the color from linefmt.
basefmt (str, default: 'C3-' ('C2-' in classic mode)) – A format string defining the properties of the baseline.
orientation ({'vertical', 'horizontal'}, default: 'vertical') – The orientation of the stems.
bottom (float, default: 0) – The y/x-position of the baseline (depending on orientation).
label (str, optional) – The label to use for the stems in legends.
data (indexable object, optional) – If given, all parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata.
- Returns:
The container may be treated like a tuple (markerline, stemlines, baseline)
- Return type:
.StemContainer
Notes
Note
This is the pyplot wrapper for .axes.Axes.stem.
See also
The MATLAB function stem which inspired this method.
- scitex.plt.step(x, y, *args, where='pre', data=None, **kwargs)[source]
Make a step plot.
Call signatures:
step(x, y, [fmt], *, data=None, where='pre', **kwargs) step(x, y, [fmt], x2, y2, [fmt2], ..., *, where='pre', **kwargs)
This is just a thin wrapper around .plot which changes some formatting options. Most of the concepts and parameters of plot can be used here as well.
Note
This method uses a standard plot with a step drawstyle: The x values are the reference positions and steps extend left/right/both directions depending on where.
For the common case where you know the values and edges of the steps, use ~.Axes.stairs instead.
- Parameters:
x (array-like) – 1D sequence of x positions. It is assumed, but not checked, that it is uniformly increasing.
y (array-like) – 1D sequence of y levels.
fmt (str, optional) –
A format string, e.g. ‘g’ for a green line. See .plot for a more detailed description.
Note: While full format strings are accepted, it is recommended to only specify the color. Line styles are currently ignored (use the keyword argument linestyle instead). Markers are accepted and plotted on the given positions, however, this is a rarely needed feature for step plots.
where ({'pre', 'post', 'mid'}, default: 'pre') –
Define where the steps should be placed:
’pre’: The y value is continued constantly to the left from every x position, i.e. the interval
(x[i-1], x[i]]has the valuey[i].’post’: The y value is continued constantly to the right from every x position, i.e. the interval
[x[i], x[i+1])has the valuey[i].’mid’: Steps occur half-way between the x positions.
data (indexable object, optional) – An object with labelled data. If given, provide the label names to plot in x and y.
**kwargs – Additional parameters are the same as those for .plot.
- Returns:
Objects representing the plotted data.
- Return type:
list of .Line2D
Notes
Note
This is the pyplot wrapper for .axes.Axes.step.
- scitex.plt.stackplot(x, *args, labels=(), colors=None, hatch=None, baseline='zero', data=None, **kwargs)[source]
Draw a stacked area plot or a streamgraph.
- Parameters:
x ((N,) array-like)
y ((M, N) array-like) –
The data can be either stacked or unstacked. Each of the following calls is legal:
stackplot(x, y) # where y has shape (M, N) e.g. y = [y1, y2, y3, y4] stackplot(x, y1, y2, y3, y4) # where y1, y2, y3, y4 have length N
baseline ({'zero', 'sym', 'wiggle', 'weighted_wiggle'}) –
Method used to calculate the baseline:
'zero': Constant zero baseline, i.e. a simple stacked plot.'sym': Symmetric around zero and is sometimes called ‘ThemeRiver’.'wiggle': Minimizes the sum of the squared slopes.'weighted_wiggle': Does the same but weights to account for size of each layer. It is also called ‘Streamgraph’-layout. More details can be found at http://leebyron.com/streamgraph/.
labels (list of str, optional) – A sequence of labels to assign to each data series. If unspecified, then no labels will be applied to artists.
colors (list of color, optional) –
A sequence of colors to be cycled through and used to color the stacked areas. The sequence need not be exactly the same length as the number of provided y, in which case the colors will repeat from the beginning.
If not specified, the colors from the Axes property cycle will be used.
hatch (list of str, default: None) –
A sequence of hatching styles. See /gallery/shapes_and_collections/hatch_style_reference. The sequence will be cycled through for filling the stacked areas from bottom to top. It need not be exactly the same length as the number of provided y, in which case the styles will repeat from the beginning.
Added in version 3.9: Support for list input
data (indexable object, optional) – If given, all parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata.**kwargs – All other keyword arguments are passed to .Axes.fill_between.
- Returns:
A list of .PolyCollection instances, one for each element in the stacked area plot.
- Return type:
list of .PolyCollection
Notes
Note
This is the pyplot wrapper for .axes.Axes.stackplot.
- scitex.plt.streamplot(x, y, u, v, density=1, linewidth=None, color=None, cmap=None, norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1, transform=None, zorder=None, start_points=None, maxlength=4.0, integration_direction='both', broken_streamlines=True, *, data=None)[source]
Draw streamlines of a vector flow.
- Parameters:
x (1D/2D arrays) – Evenly spaced strictly increasing arrays to make a grid. If 2D, all rows of x must be equal and all columns of y must be equal; i.e., they must be as if generated by
np.meshgrid(x_1d, y_1d).y (1D/2D arrays) – Evenly spaced strictly increasing arrays to make a grid. If 2D, all rows of x must be equal and all columns of y must be equal; i.e., they must be as if generated by
np.meshgrid(x_1d, y_1d).u (2D arrays) – x and y-velocities. The number of rows and columns must match the length of y and x, respectively.
v (2D arrays) – x and y-velocities. The number of rows and columns must match the length of y and x, respectively.
density (float or (float, float)) – Controls the closeness of streamlines. When
density = 1, the domain is divided into a 30x30 grid. density linearly scales this grid. Each cell in the grid can have, at most, one traversing streamline. For different densities in each direction, use a tuple (density_x, density_y).linewidth (float or 2D array) – The width of the streamlines. With a 2D array the line width can be varied across the grid. The array must have the same shape as u and v.
color (color or 2D array) – The streamline color. If given an array, its values are converted to colors using cmap and norm. The array must have the same shape as u and v.
cmap – Data normalization and colormapping parameters for color; only used if color is an array of floats. See ~.Axes.imshow for a detailed description.
norm – Data normalization and colormapping parameters for color; only used if color is an array of floats. See ~.Axes.imshow for a detailed description.
arrowsize (float) – Scaling factor for the arrow size.
arrowstyle (str) – Arrow style specification. See ~matplotlib.patches.FancyArrowPatch.
minlength (float) – Minimum length of streamline in axes coordinates.
start_points ((N, 2) array) – Coordinates of starting points for the streamlines in data coordinates (the same coordinates as the x and y arrays).
zorder (float) – The zorder of the streamlines and arrows. Artists with lower zorder values are drawn first.
maxlength (float) – Maximum length of streamline in axes coordinates.
integration_direction ({'forward', 'backward', 'both'}, default: 'both') – Integrate the streamline in forward, backward or both directions.
data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x, y, u, v, start_points
broken_streamlines (boolean, default: True) – If False, forces streamlines to continue until they leave the plot domain. If True, they may be terminated if they come too close to another streamline.
- Returns:
Container object with attributes
lines: .LineCollection of streamlinesarrows: .PatchCollection containing .FancyArrowPatch objects representing the arrows half-way along streamlines.
This container will probably change in the future to allow changes to the colormap, alpha, etc. for both lines and arrows, but these changes should be backward compatible.
- Return type:
StreamplotSet
Notes
Note
This is the pyplot wrapper for .axes.Axes.streamplot.
- scitex.plt.quiver(*args, data=None, **kwargs)[source]
Plot a 2D field of arrows.
Call signature:
quiver([X, Y], U, V, [C], /, **kwargs)
X, Y define the arrow locations, U, V define the arrow directions, and C optionally sets the color. The arguments X, Y, U, V, C are positional-only.
Arrow length
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 arrow shape is determined by width, headwidth, headlength and headaxislength. See the notes below.
Arrow styling
Each arrow is internally represented by a filled polygon with a default edge linewidth of 0. As a result, an arrow is rather a filled area, not a line with a head, and .PolyCollection properties like linewidth, edgecolor, facecolor, etc. act accordingly.
- 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 caselen(X)andlen(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 caselen(X)andlen(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. The interpretation of these components (in data or in screen space) depends on angles.
U and V must have the same number of elements, matching the number of arrow locations in X, Y. U and V may be masked. Locations masked in any of U, V, and C will not be drawn.
V (1D or 2D array-like) –
The x and y direction components of the arrow vectors. The interpretation of these components (in data or in screen space) depends on angles.
U and V must have the same number of elements, matching the number of arrow locations in X, Y. U and V may be masked. Locations masked in any of U, V, and C will not 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.
angles ({'uv', 'xy'} or array-like, default: 'uv') –
Method for determining the angle of the arrows.
’uv’: Arrow directions are based on display coordinates; i.e. a 45° angle will always show up as diagonal on the screen, irrespective of figure or Axes aspect ratio or Axes data ranges. This is useful when the arrows represent a quantity whose direction is not tied to the x and y data coordinates.
If U == V the orientation of the arrow on the plot is 45 degrees counter-clockwise from the horizontal axis (positive to the right).
’xy’: Arrow direction in data coordinates, i.e. the arrows point from (x, y) to (x+u, y+v). This is ideal for vector fields or gradient plots where the arrows should directly represent movements or gradients in the x and y directions.
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.
For example,
angles=[30, 60, 90]will orient the arrows at 30, 60, and 90 degrees respectively, regardless of the U and V components.
Note: inverting a data axis will correspondingly invert the arrows only with
angles='xy'.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’.
scale (float, optional) –
Scales the length of the arrow inversely.
Number of data values represented by one unit of arrow length on the plot. For example, if the data represents velocity in meters per second (m/s), the scale parameter determines how many meters per second correspond to one unit of arrow length relative to the width of the plot. Smaller scale parameter makes the arrow longer.
By default, an autoscaling algorithm is used to scale the arrow length to a reasonable size, which is 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'}, default: 'width') –
The physical image unit, which is used for rendering the scaled arrow data U, V.
The rendered arrow length is given by
length in x direction = $frac{u}{mathrm{scale}} mathrm{scale_unit}$
length in y direction = $frac{v}{mathrm{scale}} mathrm{scale_unit}$
For example,
(u, v) = (0.5, 0)withscale=10, scale_units="width"results in a horizontal arrow with a length of 0.5 / 10 * “width”, i.e. 0.05 times the Axes width.Supported values are:
- ’width’ or ‘height’: The arrow length is scaled relative to the width or height
of the Axes. For example,
scale_units='width', scale=1.0, will result in an arrow length of width of the Axes.
’dots’: The arrow length of the arrows is in measured in display dots (pixels).
- ’inches’: Arrow lengths are scaled based on the DPI (dots per inch) of the figure.
This ensures that the arrows have a consistent physical size on the figure, in inches, regardless of data values or plot scaling. For example,
(u, v) = (1, 0)withscale_units='inches', scale=2results in a 0.5 inch-long arrow.
- ’x’ or ‘y’: The arrow length is scaled relative to the x or y axis units.
For example,
(u, v) = (0, 1)withscale_units='x', scale=1results in a vertical arrow with the length of 1 x-axis unit.
- ’xy’: Arrow length will be same as ‘x’ or ‘y’ units.
This is useful for creating vectors in the x-y plane where u and v have the same units as x and y. 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.
Note: Setting scale_units without setting scale does not have any effect because the scale units only differ by a constant factor and that is rescaled through autoscaling.
units ({'width', 'height', 'dots', 'inches', 'x', 'y', 'xy'}, default: 'width') –
Affects the arrow size (except for the length). In particular, the shaft width is measured in multiples of this unit.
Supported values are:
’width’, ‘height’: The width or height of the Axes.
’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 following table summarizes how these values affect the visible arrow size under zooming and figure size changes:
units
zoom
figure size change
’x’, ‘y’, ‘xy’
arrow size scales
—
‘width’, ‘height’
—
arrow size scales
’dots’, ‘inches’
—
—
width (float, optional) –
Shaft width in arrow units. All head parameters are relative to width.
The 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. See the notes below.
headlength (float, default: 5) – Head length as multiple of shaft width. See the notes below.
headaxislength (float, default: 4.5) – Head length at shaft intersection as multiple of shaft width. See the notes below.
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.
color (color or list color, 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.
data (indexable object, optional) – If given, all parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata.**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 and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased or aa or antialiaseds: bool or list of bools array: array-like or None capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clim: (vmin: float, vmax: float) clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: color or list of RGBA tuples edgecolor or ec or edgecolors: color or list of color or ‘face’ facecolor or facecolors or fc: color or list of color figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown 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 mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .AbstractPathEffect paths: list of array-like picker: None or bool or float or callable pickradius: float rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str urls: list of str or None verts: list of array-like verts_and_codes: unknown visible: bool zorder: float
- Return type:
~matplotlib.quiver.Quiver
See also
Axes.quiverkeyAdd a key to a quiver plot.
Notes
Note
This is the pyplot wrapper for .axes.Axes.quiver.
Arrow shape
The arrow is drawn as a polygon using the nodes as shown below. The values headwidth, headlength, and headaxislength are in units of width.
The defaults give a slightly swept-back arrow. Here are some guidelines how to get other head shapes:
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 proportionally.
To remove the head completely, set all head parameters to 0.
To get a diamond-shaped head, make headaxislength larger than headlength.
Warning: For headaxislength < (headlength / headwidth), the “headaxis” nodes (i.e. the ones connecting the head with the shaft) will protrude out of the head in forward direction so that the arrow head looks broken.
- scitex.plt.barbs(*args, data=None, **kwargs)[source]
Plot a 2D field of wind barbs.
Call signature:
barbs([X, Y], U, V, [C], /, **kwargs)
Where X, Y define the barb locations, U, V define the barb directions, and C optionally sets the color.
The arguments X, Y, U, V, C are positional-only and may be 1D or 2D. U, V, C may be masked arrays, but masked X, Y are not supported at present.
Barbs are traditionally used in meteorology as a way to plot the speed and direction of wind observations, but can technically be used to plot any two dimensional vector quantity. As opposed to arrows, which give vector magnitude by the length of the arrow, the barbs give more quantitative information about the vector magnitude by putting slanted lines or a triangle for various increments in magnitude, as show schematically below:
: /\ \ : / \ \ : / \ \ \ : / \ \ \ : ------------------------------
The largest increment is given by a triangle (or “flag”). After those come full lines (barbs). The smallest increment is a half line. There is only, of course, ever at most 1 half line. If the magnitude is small and only needs a single half-line and no full lines or triangles, the half-line is offset from the end of the barb so that it can be easily distinguished from barbs with a single full line. The magnitude for the barb shown above would nominally be 65, using the standard increments of 50, 10, and 5.
See also https://en.wikipedia.org/wiki/Wind_barb.
- Parameters:
X (1D or 2D array-like, optional) –
The x and y coordinates of the barb locations. See pivot for how the barbs are drawn to the x, y positions.
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 caselen(X)andlen(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 barb locations. See pivot for how the barbs are drawn to the x, y positions.
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 caselen(X)andlen(Y)must match the column and row dimensions of U and V.U (1D or 2D array-like) – The x and y components of the barb shaft.
V (1D or 2D array-like) – The x and y components of the barb shaft.
C (1D or 2D array-like, optional) –
Numeric data that defines the barb colors by colormapping via norm and cmap.
This does not support explicit colors. If you want to set colors directly, use barbcolor instead.
length (float, default: 7) – Length of the barb in points; the other parts of the barb are scaled against this.
pivot ({'tip', 'middle'} or float, default: 'tip') – The part of the arrow that is anchored to the X, Y grid. The barb rotates about this point. This can also be a number, which shifts the start of the barb that many points away from grid point.
barbcolor (color or color sequence) – The color of all parts of the barb except for the flags. This parameter is analogous to the edgecolor parameter for polygons, which can be used instead. However this parameter will override facecolor.
flagcolor (color or color sequence) – The color of any flags on the barb. This parameter is analogous to the facecolor parameter for polygons, which can be used instead. However, this parameter will override facecolor. If this is not set (and C has not either) then flagcolor will be set to match barbcolor so that the barb has a uniform color. If C has been set, flagcolor has no effect.
sizes (dict, optional) –
A dictionary of coefficients specifying the ratio of a given feature to the length of the barb. Only those values one wishes to override need to be included. These features include:
’spacing’ - space between features (flags, full/half barbs)
’height’ - height (distance from shaft to top) of a flag or full barb
’width’ - width of a flag, twice the width of a full barb
’emptybarb’ - radius of the circle used for low magnitudes
fill_empty (bool, default: False) – Whether the empty barbs (circles) that are drawn should be filled with the flag color. If they are not filled, the center is transparent.
rounding (bool, default: True) – Whether the vector magnitude should be rounded when allocating barb components. If True, the magnitude is rounded to the nearest multiple of the half-barb increment. If False, the magnitude is simply truncated to the next lowest multiple.
barb_increments (dict, optional) –
A dictionary of increments specifying values to associate with different parts of the barb. Only those values one wishes to override need to be included.
’half’ - half barbs (Default is 5)
’full’ - full barbs (Default is 10)
’flag’ - flags (default is 50)
flip_barb (bool or array-like of bool, default: False) –
Whether the lines and flags should point opposite to normal. Normal behavior is for the barbs and lines to point right (comes from wind barbs having these features point towards low pressure in the Northern Hemisphere).
A single value is applied to all barbs. Individual barbs can be flipped by passing a bool array of the same size as U and V.
data (indexable object, optional) – If given, all parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata.**kwargs –
The barbs can further be customized using .PolyCollection keyword arguments:
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 and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased or aa or antialiaseds: bool or list of bools array: array-like or None capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clim: (vmin: float, vmax: float) clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: color or list of RGBA tuples edgecolor or ec or edgecolors: color or list of color or ‘face’ facecolor or facecolors or fc: color or list of color figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown 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 mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .AbstractPathEffect paths: list of array-like picker: None or bool or float or callable pickradius: float rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str urls: list of str or None verts: list of array-like verts_and_codes: unknown visible: bool zorder: float
- Returns:
barbs
- Return type:
~matplotlib.quiver.Barbs
Notes
Note
This is the pyplot wrapper for .axes.Axes.barbs.
- scitex.plt.hexbin(x, y, C=None, gridsize=100, bins=None, xscale='linear', yscale='linear', extent=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors='face', reduce_C_function=<function mean>, mincnt=None, marginals=False, colorizer=None, *, data=None, **kwargs)[source]
Make a 2D hexagonal binning plot of points x, y.
If C is None, the value of the hexagon is determined by the number of points in the hexagon. Otherwise, C specifies values at the coordinate (x[i], y[i]). For each hexagon, these values are reduced using reduce_C_function.
- Parameters:
x (array-like) – The data positions. x and y must be of the same length.
y (array-like) – The data positions. x and y must be of the same length.
C (array-like, optional) – If given, these values are accumulated in the bins. Otherwise, every point has a value of 1. Must be of the same length as x and y.
gridsize (int or (int, int), default: 100) –
If a single int, the number of hexagons in the x-direction. The number of hexagons in the y-direction is chosen such that the hexagons are approximately regular.
Alternatively, if a tuple (nx, ny), the number of hexagons in the x-direction and the y-direction. In the y-direction, counting is done along vertically aligned hexagons, not along the zig-zag chains of hexagons; see the following illustration.
To get approximately regular hexagons, choose \(n_x = \sqrt{3}\,n_y\).
bins ('log' or int or sequence, default: None) –
Discretization of the hexagon values.
If None, no binning is applied; the color of each hexagon directly corresponds to its count value.
If ‘log’, use a logarithmic scale for the colormap. Internally, \(log_{10}(i+1)\) is used to determine the hexagon color. This is equivalent to
norm=LogNorm().If an integer, divide the counts in the specified number of bins, and color the hexagons accordingly.
If a sequence of values, the values of the lower bound of the bins to be used.
xscale ({'linear', 'log'}, default: 'linear') – Use a linear or log10 scale on the horizontal axis.
yscale ({'linear', 'log'}, default: 'linear') – Use a linear or log10 scale on the vertical axis.
mincnt (int >= 0, default: None) – If not None, only display cells with at least mincnt number of points in the cell.
marginals (bool, default: False) – If marginals is True, plot the marginal density as colormapped rectangles along the bottom of the x-axis and left of the y-axis.
extent (4-tuple of float, default: None) –
The limits of the bins (xmin, xmax, ymin, ymax). The default assigns the limits based on gridsize, x, y, xscale and yscale.
If xscale or yscale is set to ‘log’, the limits are expected to be the exponent for a power of 10. E.g. for x-limits of 1 and 50 in ‘linear’ scale and y-limits of 10 and 1000 in ‘log’ scale, enter (1, 50, 1, 3).
cmap (str or ~matplotlib.colors.Colormap, default:
rcParams[“image.cmap”](default:'viridis')) – The Colormap instance or registered colormap name used to map scalar data to colors.norm (str or ~matplotlib.colors.Normalize, optional) –
The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.
If given, this can be one of the following:
An instance of .Normalize or one of its subclasses (see Colormap normalization).
A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
alpha (float between 0 and 1, optional) – The alpha blending value, between 0 (transparent) and 1 (opaque).
linewidths (float, default: None) – If None, defaults to
rcParams[“patch.linewidth”](default:1.0).edgecolors ({‘face’, ‘none’, None} or color, default: ‘face’) –
The color of the hexagon edges. Possible values are:
’face’: Draw the edges in the same color as the fill color.
’none’: No edges are drawn. This can sometimes lead to unsightly unpainted pixels between the hexagons.
None: Draw outlines in the default color.
An explicit color.
reduce_C_function (callable, default: numpy.mean) –
The function to aggregate C within the bins. It is ignored if C is not given. This must have the signature:
def reduce_C_function(C: array) -> float
Commonly used functions are:
numpy.mean: average of the points
numpy.sum: integral of the point values
numpy.amax: value taken from the largest point
By default will only reduce cells with at least 1 point because some reduction functions (such as numpy.amax) will error/warn with empty input. Changing mincnt will adjust the cutoff, and if set to 0 will pass empty input to the reduction function.
colorizer (~matplotlib.colorizer.Colorizer or None, default: None) – The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.
data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x, y, C
**kwargs (~matplotlib.collections.PolyCollection properties) –
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 and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased or aa or antialiaseds: bool or list of bools array: array-like or None capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clim: (vmin: float, vmax: float) clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: color or list of RGBA tuples edgecolor or ec or edgecolors: color or list of color or ‘face’ facecolor or facecolors or fc: color or list of color figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown 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 mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .AbstractPathEffect paths: list of array-like picker: None or bool or float or callable pickradius: float rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str urls: list of str or None verts: list of array-like verts_and_codes: unknown visible: bool zorder: float
- Returns:
A .PolyCollection defining the hexagonal bins.
.PolyCollection.get_offsets contains a Mx2 array containing the x, y positions of the M hexagon centers in data coordinates.
.PolyCollection.get_array contains the values of the M hexagons.
If marginals is True, horizontal bar and vertical bar (both PolyCollections) will be attached to the return collection as attributes hbar and vbar.
- Return type:
~matplotlib.collections.PolyCollection
See also
hist2d2D histogram rectangular bins
Notes
Note
This is the pyplot wrapper for .axes.Axes.hexbin.
- scitex.plt.pcolormesh(*args, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, colorizer=None, shading=None, antialiased=False, data=None, **kwargs)[source]
Create a pseudocolor plot with a non-regular rectangular grid.
Call signature:
pcolormesh([X, Y,] C, /, **kwargs)
X and Y can be used to specify the corners of the quadrilaterals.
The arguments X, Y, C are positional-only.
Hint
~.Axes.pcolormesh is similar to ~.Axes.pcolor. It is much faster and preferred in most cases. For a detailed discussion on the differences see Differences between pcolor() and pcolormesh().
- Parameters:
C (array-like) –
The mesh data. Supported array shapes are:
(M, N) or M*N: a mesh 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 mesh data.
X (array-like, optional) –
The coordinates of the corners of quadrilaterals of a pcolormesh:
(X[i+1, j], Y[i+1, j]) (X[i+1, j+1], Y[i+1, j+1]) ●╶───╴● │ │ ●╶───╴● (X[i, j], Y[i, j]) (X[i, j+1], Y[i, j+1])Note that the column index corresponds to the x-coordinate, and the row index corresponds to y. For details, see the Notes section below.
If
shading='flat'the dimensions of X and Y should be one greater than those of C, and the quadrilateral is colored due to the value atC[i, j]. If X, Y and C have equal dimensions, a warning will be raised and the last row and column of C will be ignored.If
shading='nearest'or'gouraud', the dimensions of X and Y should be the same as those of C (if not, a ValueError will be raised). For'nearest'the colorC[i, j]is centered on(X[i, j], Y[i, j]). For'gouraud', a smooth interpolation is carried out between the quadrilateral corners.If X and/or Y are 1-D arrays or column vectors they will be expanded as needed into the appropriate 2D arrays, making a rectangular grid.
Y (array-like, optional) –
The coordinates of the corners of quadrilaterals of a pcolormesh:
(X[i+1, j], Y[i+1, j]) (X[i+1, j+1], Y[i+1, j+1]) ●╶───╴● │ │ ●╶───╴● (X[i, j], Y[i, j]) (X[i, j+1], Y[i, j+1])Note that the column index corresponds to the x-coordinate, and the row index corresponds to y. For details, see the Notes section below.
If
shading='flat'the dimensions of X and Y should be one greater than those of C, and the quadrilateral is colored due to the value atC[i, j]. If X, Y and C have equal dimensions, a warning will be raised and the last row and column of C will be ignored.If
shading='nearest'or'gouraud', the dimensions of X and Y should be the same as those of C (if not, a ValueError will be raised). For'nearest'the colorC[i, j]is centered on(X[i, j], Y[i, j]). For'gouraud', a smooth interpolation is carried out between the quadrilateral corners.If X and/or Y are 1-D arrays or column vectors they will be expanded as needed into the appropriate 2D arrays, making a rectangular grid.
cmap (str or ~matplotlib.colors.Colormap, default:
rcParams[“image.cmap”](default:'viridis')) – The Colormap instance or registered colormap name used to map scalar data to colors.norm (str or ~matplotlib.colors.Normalize, optional) –
The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.
If given, this can be one of the following:
An instance of .Normalize or one of its subclasses (see Colormap normalization).
A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
colorizer (~matplotlib.colorizer.Colorizer or None, default: None) – The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.
edgecolors ({'none', None, 'face', color, color sequence}, optional) –
The color of the edges. Defaults to ‘none’. Possible values:
’none’ or ‘’: No edge.
None:
rcParams[“patch.edgecolor”](default:'black') will be used. Note that currentlyrcParams[“patch.force_edgecolor”](default:False) has to be True for this to work.’face’: Use the adjacent face color.
A color or sequence of colors will set the edge color.
The singular form edgecolor works as an alias.
alpha (float, default: None) – The alpha blending value, between 0 (transparent) and 1 (opaque).
shading ({'flat', 'nearest', 'gouraud', 'auto'}, optional) –
The fill style for the quadrilateral; defaults to
rcParams[“pcolor.shading”](default:'auto'). Possible values:’flat’: A solid color is used for each quad. The color of the quad (i, j), (i+1, j), (i, j+1), (i+1, j+1) is given by
C[i, j]. The dimensions of X and Y should be one greater than those of C; if they are the same as C, then a deprecation warning is raised, and the last row and column of C are dropped.’nearest’: Each grid point will have a color centered on it, extending halfway between the adjacent grid centers. The dimensions of X and Y must be the same as C.
’gouraud’: Each quad will be Gouraud shaded: The color of the corners (i’, j’) are given by
C[i', j']. The color values of the area in between is interpolated from the corner values. The dimensions of X and Y must be the same as C. When Gouraud shading is used, edgecolors is ignored.’auto’: Choose ‘flat’ if dimensions of X and Y are one larger than C. Choose ‘nearest’ if dimensions are the same.
See /gallery/images_contours_and_fields/pcolormesh_grids for more description.
snap (bool, default: False) – Whether to snap the mesh to pixel boundaries.
rasterized (bool, optional) – Rasterize the pcolormesh when drawing vector graphics. This can speed up rendering and produce smaller files for large data sets. See also /gallery/misc/rasterization_demo.
data (indexable object, optional) – If given, all parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata.**kwargs – Additionally, the following arguments are allowed. They are passed along to the ~matplotlib.collections.QuadMesh constructor:
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 and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased or aa or antialiaseds: bool or list of bools array: array-like capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clim: (vmin: float, vmax: float) clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: color or list of RGBA tuples edgecolor or ec or edgecolors: color or list of color or ‘face’ facecolor or facecolors or fc: color or list of color figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown 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 mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .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: ~matplotlib.transforms.Transform url: str urls: list of str or None visible: bool zorder: float
- Return type:
matplotlib.collections.QuadMesh
See also
pcolorAn alternative implementation with slightly different features. For a detailed discussion on the differences see Differences between pcolor() and pcolormesh().
imshowIf X and Y are each equidistant, ~.Axes.imshow can be a faster alternative.
Notes
Note
This is the pyplot wrapper for .axes.Axes.pcolormesh.
Masked arrays
C may be a masked array. If
C[i, j]is masked, the corresponding quadrilateral will be transparent. Masking of X and Y is not supported. Use ~.Axes.pcolor if you need this functionality.Grid orientation
The grid orientation follows the standard matrix convention: An array C with shape (nrows, ncolumns) is plotted with the column number as X and the row number as Y.
Differences between pcolor() and pcolormesh()
Both methods are used to create a pseudocolor plot of a 2D array using quadrilaterals.
The main difference lies in the created object and internal data handling: While ~.Axes.pcolor returns a .PolyQuadMesh, ~.Axes.pcolormesh returns a .QuadMesh. The latter is more specialized for the given purpose and thus is faster. It should almost always be preferred.
There is also a slight difference in the handling of masked arrays. Both ~.Axes.pcolor and ~.Axes.pcolormesh support masked arrays for C. However, only ~.Axes.pcolor supports masked arrays for X and Y. The reason lies in the internal handling of the masked values. ~.Axes.pcolor leaves out the respective polygons from the PolyQuadMesh. ~.Axes.pcolormesh sets the facecolor of the masked elements to transparent. You can see the difference when using edgecolors. While all edges are drawn irrespective of masking in a QuadMesh, the edge between two adjacent masked quadrilaterals in ~.Axes.pcolor is not drawn as the corresponding polygons do not exist in the PolyQuadMesh. Because PolyQuadMesh draws each individual polygon, it also supports applying hatches and linestyles to the collection.
Another difference is the support of Gouraud shading in ~.Axes.pcolormesh, which is not available with ~.Axes.pcolor.
- scitex.plt.tripcolor(*args, alpha=1.0, norm=None, cmap=None, vmin=None, vmax=None, shading='flat', facecolors=None, **kwargs)[source]
Create a pseudocolor plot of an unstructured triangular grid.
Call signatures:
tripcolor(triangulation, c, *, ...) tripcolor(x, y, c, *, [triangles=triangles], [mask=mask], ...)
The triangular grid can be specified either by passing a .Triangulation object as the first parameter, or by passing the points x, y and optionally the triangles and a mask. See .Triangulation for an explanation of these parameters.
It is possible to pass the triangles positionally, i.e.
tripcolor(x, y, triangles, c, ...). However, this is discouraged. For more clarity, pass triangles via keyword argument.If neither of triangulation or triangles are given, the triangulation is calculated on the fly. In this case, it does not make sense to provide colors at the triangle faces via c or facecolors because there are multiple possible triangulations for a group of points and you don’t know which triangles will be constructed.
- Parameters:
triangulation (.Triangulation) – An already created triangular grid.
x – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.
y – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.
triangles – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.
mask – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.
c (array-like) – The color values, either for the points or for the triangles. Which one is automatically inferred from the length of c, i.e. does it match the number of points or the number of triangles. If there are the same number of points and triangles in the triangulation it is assumed that color values are defined at points; to force the use of color values at triangles use the keyword argument
facecolors=cinstead of justc. This parameter is position-only.facecolors (array-like, optional) – Can be used alternatively to c to specify colors at the triangle faces. This parameter takes precedence over c.
shading ({'flat', 'gouraud'}, default: 'flat') – If ‘flat’ and the color values c are defined at points, the color values used for each triangle are from the mean c of the triangle’s three points. If shading is ‘gouraud’ then color values must be defined at points.
cmap (str or ~matplotlib.colors.Colormap, default:
rcParams[“image.cmap”](default:'viridis')) – The Colormap instance or registered colormap name used to map scalar data to colors.norm (str or ~matplotlib.colors.Normalize, optional) –
The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.
If given, this can be one of the following:
An instance of .Normalize or one of its subclasses (see Colormap normalization).
A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
colorizer (~matplotlib.colorizer.Colorizer or None, default: None) – The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.
**kwargs (~matplotlib.collections.Collection 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 and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased or aa or antialiaseds: bool or list of bools array: array-like or None capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clim: (vmin: float, vmax: float) clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: color or list of RGBA tuples edgecolor or ec or edgecolors: color or list of color or ‘face’ facecolor or facecolors or fc: color or list of color figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown 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 mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .AbstractPathEffect paths: unknown 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: ~matplotlib.transforms.Transform url: str urls: list of str or None visible: bool zorder: float
- Returns:
The result depends on shading: For
shading='flat'the result is a .PolyCollection, forshading='gouraud'the result is a .TriMesh.- Return type:
~matplotlib.collections.PolyCollection or ~matplotlib.collections.TriMesh
Notes
Note
This is the pyplot wrapper for .axes.Axes.tripcolor.
- scitex.plt.tricontour(*args, **kwargs)[source]
Draw contour lines on an unstructured triangular grid.
Call signatures:
tricontour(triangulation, z, [levels], ...) tricontour(x, y, z, [levels], *, [triangles=triangles], [mask=mask], ...)
The triangular grid can be specified either by passing a .Triangulation object as the first parameter, or by passing the points x, y and optionally the triangles and a mask. See .Triangulation for an explanation of these parameters. If neither of triangulation or triangles are given, the triangulation is calculated on the fly.
It is possible to pass triangles positionally, i.e.
tricontour(x, y, triangles, z, ...). However, this is discouraged. For more clarity, pass triangles via keyword argument.- Parameters:
triangulation (.Triangulation, optional) – An already created triangular grid.
x – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.
y – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.
triangles – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.
mask – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.
z (array-like) –
The height values over which the contour is drawn. Color-mapping is controlled by cmap, norm, vmin, and vmax.
Note
All values in z must be finite. Hence, nan and inf values must either be removed or ~.Triangulation.set_mask be used.
levels (int or array-like, optional) –
Determines the number and positions of the contour lines / regions.
If an int n, use ~matplotlib.ticker.MaxNLocator, which tries to automatically choose no more than n+1 “nice” contour levels between between minimum and maximum numeric values of Z.
If array-like, draw contour lines at the specified levels. The values must be in increasing order.
colors (color or list of color, optional) –
The colors of the levels, i.e., the contour lines.
The sequence is cycled for the levels in ascending order. If the sequence is shorter than the number of levels, it is repeated.
As a shortcut, single color strings may be used in place of one-element lists, i.e.
'red'instead of['red']to color all levels with the same color. This shortcut does only work for color strings, not for other ways of specifying colors.By default (value None), the colormap specified by cmap will be used.
alpha (float, default: 1) – The alpha blending value, between 0 (transparent) and 1 (opaque).
cmap (str or ~matplotlib.colors.Colormap, default:
rcParams[“image.cmap”](default:'viridis')) –The Colormap instance or registered colormap name used to map scalar data to colors.
This parameter is ignored if colors is set.
norm (str or ~matplotlib.colors.Normalize, optional) –
The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.
If given, this can be one of the following:
An instance of .Normalize or one of its subclasses (see Colormap normalization).
A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.
This parameter is ignored if colors is set.
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
If vmin or vmax are not given, the default color scaling is based on levels.
This parameter is ignored if colors is set.
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
If vmin or vmax are not given, the default color scaling is based on levels.
This parameter is ignored if colors is set.
origin ({None, ‘upper’, ‘lower’, ‘image’}, default: None) –
Determines the orientation and exact position of z by specifying the position of
z[0, 0]. This is only relevant, if X, Y are not given.None:
z[0, 0]is at X=0, Y=0 in the lower left corner.’lower’:
z[0, 0]is at X=0.5, Y=0.5 in the lower left corner.’upper’:
z[0, 0]is at X=N+0.5, Y=0.5 in the upper left corner.’image’: Use the value from
rcParams[“image.origin”](default:'upper').
extent ((x0, x1, y0, y1), optional) –
If origin is not None, then extent is interpreted as in .imshow: it gives the outer pixel boundaries. In this case, the position of z[0, 0] is the center of the pixel, not a corner. If origin is None, then (x0, y0) is the position of z[0, 0], and (x1, y1) is the position of z[-1, -1].
This argument is ignored if X and Y are specified in the call to contour.
locator (ticker.Locator subclass, optional) – The locator is used to determine the contour levels if they are not given explicitly via levels. Defaults to ~.ticker.MaxNLocator.
extend ({'neither', 'both', 'min', 'max'}, default: 'neither') –
Determines the
tricontour-coloring of values that are outside the levels range.If ‘neither’, values outside the levels range are not colored. If ‘min’, ‘max’ or ‘both’, color the values below, above or below and above the levels range.
Values below
min(levels)and abovemax(levels)are mapped to the under/over values of the .Colormap. Note that most colormaps do not have dedicated colors for these by default, so that the over and under values are the edge values of the colormap. You may want to set these values explicitly using .Colormap.set_under and .Colormap.set_over.Note
An existing .TriContourSet does not get notified if properties of its colormap are changed. Therefore, an explicit call to .ContourSet.changed() is needed after modifying the colormap. The explicit call can be left out, if a colorbar is assigned to the .TriContourSet because it internally calls .ContourSet.changed().
xunits (registered units, optional) – Override axis units by specifying an instance of a
matplotlib.units.ConversionInterface.yunits (registered units, optional) – Override axis units by specifying an instance of a
matplotlib.units.ConversionInterface.antialiased (bool, optional) – Enable antialiasing, overriding the defaults. For filled contours, the default is True. For line contours, it is taken from
rcParams[“lines.antialiased”](default:True).linewidths (float or array-like, default:
rcParams[“contour.linewidth”](default:None)) –The line width of the contour lines.
If a number, all levels will be plotted with this linewidth.
If a sequence, the levels in ascending order will be plotted with the linewidths in the order specified.
If None, this falls back to
rcParams[“lines.linewidth”](default:1.5).linestyles ({None, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’}, optional) –
If linestyles is None, the default is ‘solid’ unless the lines are monochrome. In that case, negative contours will take their linestyle from
rcParams[“contour.negative_linestyle”](default:'dashed') setting.linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary.
- Return type:
~matplotlib.tri.TriContourSet
Notes
Note
This is the pyplot wrapper for .axes.Axes.tricontour.
- scitex.plt.tricontourf(*args, **kwargs)[source]
Draw contour regions on an unstructured triangular grid.
Call signatures:
tricontourf(triangulation, z, [levels], ...) tricontourf(x, y, z, [levels], *, [triangles=triangles], [mask=mask], ...)
The triangular grid can be specified either by passing a .Triangulation object as the first parameter, or by passing the points x, y and optionally the triangles and a mask. See .Triangulation for an explanation of these parameters. If neither of triangulation or triangles are given, the triangulation is calculated on the fly.
It is possible to pass triangles positionally, i.e.
tricontourf(x, y, triangles, z, ...). However, this is discouraged. For more clarity, pass triangles via keyword argument.- Parameters:
triangulation (.Triangulation, optional) – An already created triangular grid.
x – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.
y – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.
triangles – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.
mask – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.
z (array-like) –
The height values over which the contour is drawn. Color-mapping is controlled by cmap, norm, vmin, and vmax.
Note
All values in z must be finite. Hence, nan and inf values must either be removed or ~.Triangulation.set_mask be used.
levels (int or array-like, optional) –
Determines the number and positions of the contour lines / regions.
If an int n, use ~matplotlib.ticker.MaxNLocator, which tries to automatically choose no more than n+1 “nice” contour levels between between minimum and maximum numeric values of Z.
If array-like, draw contour lines at the specified levels. The values must be in increasing order.
colors (color or list of color, optional) –
The colors of the levels, i.e., the contour regions.
The sequence is cycled for the levels in ascending order. If the sequence is shorter than the number of levels, it is repeated.
As a shortcut, single color strings may be used in place of one-element lists, i.e.
'red'instead of['red']to color all levels with the same color. This shortcut does only work for color strings, not for other ways of specifying colors.By default (value None), the colormap specified by cmap will be used.
alpha (float, default: 1) – The alpha blending value, between 0 (transparent) and 1 (opaque).
cmap (str or ~matplotlib.colors.Colormap, default:
rcParams[“image.cmap”](default:'viridis')) –The Colormap instance or registered colormap name used to map scalar data to colors.
This parameter is ignored if colors is set.
norm (str or ~matplotlib.colors.Normalize, optional) –
The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.
If given, this can be one of the following:
An instance of .Normalize or one of its subclasses (see Colormap normalization).
A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.
This parameter is ignored if colors is set.
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
If vmin or vmax are not given, the default color scaling is based on levels.
This parameter is ignored if colors is set.
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 an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).
If vmin or vmax are not given, the default color scaling is based on levels.
This parameter is ignored if colors is set.
origin ({None, ‘upper’, ‘lower’, ‘image’}, default: None) –
Determines the orientation and exact position of z by specifying the position of
z[0, 0]. This is only relevant, if X, Y are not given.None:
z[0, 0]is at X=0, Y=0 in the lower left corner.’lower’:
z[0, 0]is at X=0.5, Y=0.5 in the lower left corner.’upper’:
z[0, 0]is at X=N+0.5, Y=0.5 in the upper left corner.’image’: Use the value from
rcParams[“image.origin”](default:'upper').
extent ((x0, x1, y0, y1), optional) –
If origin is not None, then extent is interpreted as in .imshow: it gives the outer pixel boundaries. In this case, the position of z[0, 0] is the center of the pixel, not a corner. If origin is None, then (x0, y0) is the position of z[0, 0], and (x1, y1) is the position of z[-1, -1].
This argument is ignored if X and Y are specified in the call to contour.
locator (ticker.Locator subclass, optional) – The locator is used to determine the contour levels if they are not given explicitly via levels. Defaults to ~.ticker.MaxNLocator.
extend ({'neither', 'both', 'min', 'max'}, default: 'neither') –
Determines the
tricontourf-coloring of values that are outside the levels range.If ‘neither’, values outside the levels range are not colored. If ‘min’, ‘max’ or ‘both’, color the values below, above or below and above the levels range.
Values below
min(levels)and abovemax(levels)are mapped to the under/over values of the .Colormap. Note that most colormaps do not have dedicated colors for these by default, so that the over and under values are the edge values of the colormap. You may want to set these values explicitly using .Colormap.set_under and .Colormap.set_over.Note
An existing .TriContourSet does not get notified if properties of its colormap are changed. Therefore, an explicit call to .ContourSet.changed() is needed after modifying the colormap. The explicit call can be left out, if a colorbar is assigned to the .TriContourSet because it internally calls .ContourSet.changed().
xunits (registered units, optional) – Override axis units by specifying an instance of a
matplotlib.units.ConversionInterface.yunits (registered units, optional) – Override axis units by specifying an instance of a
matplotlib.units.ConversionInterface.antialiased (bool, optional) – Enable antialiasing, overriding the defaults. For filled contours, the default is True. For line contours, it is taken from
rcParams[“lines.antialiased”](default:True).hatches (list[str], optional) – A list of crosshatch patterns to use on the filled areas. If None, no hatching will be added to the contour.
- Return type:
~matplotlib.tri.TriContourSet
Notes
Note
This is the pyplot wrapper for .axes.Axes.tricontourf.
.tricontourf fills intervals that are closed at the top; that is, for boundaries z1 and z2, the filled region is:
z1 < Z <= z2
except for the lowest interval, which is closed on both sides (i.e. it includes the lowest value).
- scitex.plt.spy(Z, precision=0, marker=None, markersize=None, aspect='equal', origin='upper', **kwargs)[source]
Plot the sparsity pattern of a 2D array.
This visualizes the non-zero values of the array.
Two plotting styles are available: image and marker. Both are available for full arrays, but only the marker style works for scipy.sparse.spmatrix instances.
Image style
If marker and markersize are None, ~.Axes.imshow is used. Any extra remaining keyword arguments are passed to this method.
Marker style
If Z is a scipy.sparse.spmatrix or marker or markersize are None, a .Line2D object will be returned with the value of marker determining the marker type, and any remaining keyword arguments passed to ~.Axes.plot.
- Parameters:
Z ((M, N) array-like) – The array to be plotted.
precision (float or 'present', default: 0) –
If precision is 0, any non-zero value will be plotted. Otherwise, values of \(|Z| > precision\) will be plotted.
For scipy.sparse.spmatrix instances, you can also pass ‘present’. In this case any value present in the array will be plotted, even if it is identically zero.
aspect ({'equal', 'auto', None} or float, default: 'equal') –
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.
’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.
None: Use
rcParams[“image.aspect”](default:'equal').
origin ({‘upper’, ‘lower’}, default:
rcParams[“image.origin”](default:'upper')) – Place the [0, 0] index of the array in the upper left or lower left corner of the Axes. The convention ‘upper’ is typically used for matrices and images.**kwargs –
The supported additional parameters depend on the plotting style.
For the image style, you can pass the following additional parameters of ~.Axes.imshow:
cmap
alpha
url
any .Artist properties (passed on to the .AxesImage)
For the marker style, you can pass any .Line2D property except for linestyle:
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 and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color 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: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: color or 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] mouseover: bool path_effects: list of .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: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float
- Returns:
The return type depends on the plotting style (see above).
- Return type:
~matplotlib.image.AxesImage or .Line2D
Notes
Note
This is the pyplot wrapper for .axes.Axes.spy.
- scitex.plt.matshow(A, fignum=None, **kwargs)[source]
Display a 2D array as a matrix in a new figure window.
The origin is set at the upper left hand corner. The indexing is
(row, column)so that the first index runs vertically and the second index runs horizontally in the figure:A[0, 0] ⋯ A[0, M-1] ⋮ ⋮ A[N-1, 0] ⋯ A[N-1, M-1]
The aspect ratio of the figure window is that of the array, unless this would make an excessively short or narrow figure.
Tick labels for the xaxis are placed on top.
- Parameters:
A (2D array-like) – The matrix to be displayed.
fignum (None or int) –
If None, create a new, appropriately sized figure window.
If 0, use the current Axes (creating one if there is none, without ever adjusting the figure size).
Otherwise, create a new Axes on the figure with the given number (creating it at the appropriate size if it does not exist, but not adjusting the figure size otherwise). Note that this will be drawn on top of any preexisting Axes on the figure.
**kwargs (~matplotlib.axes.Axes.imshow arguments)
- Return type:
~matplotlib.image.AxesImage
- scitex.plt.specgram(x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, cmap=None, xextent=None, pad_to=None, sides=None, scale_by_freq=None, mode=None, scale=None, vmin=None, vmax=None, *, data=None, **kwargs)[source]
Plot a spectrogram.
Compute and plot a spectrogram of data in x. Data are split into NFFT length segments and the spectrum of each section is computed. The windowing function window is applied to each segment, and the amount of overlap of each segment is specified with noverlap. The spectrogram is plotted as a colormap (using imshow).
- Parameters:
x (1-D array or sequence) – Array or sequence containing the data.
Fs (float, default: 2) – The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.
window (callable or ndarray, default: .window_hanning) – A function or a vector of length NFFT. To create window vectors see .window_hanning, .window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.
sides ({'default', 'onesided', 'twosided'}, optional) – Which sides of the spectrum to return. ‘default’ is one-sided for real data and two-sided for complex data. ‘onesided’ forces the return of a one-sided spectrum, while ‘twosided’ forces two-sided.
pad_to (int, optional) – The number of points to which the data segment is padded when performing the FFT. This can be different from NFFT, which specifies the number of data points used. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to ~numpy.fft.fft. The default is None, which sets pad_to equal to NFFT
NFFT (int, default: 256) – The number of data points used in each block for the FFT. A power 2 is most efficient. This should NOT be used to get zero padding, or the scaling of the result will be incorrect; use pad_to for this instead.
detrend ({'none', 'mean', 'linear'} or callable, default: 'none') – The function applied to each segment before fft-ing, designed to remove the mean or linear trend. Unlike in MATLAB, where the detrend parameter is a vector, in Matplotlib it is a function. The
mlabmodule defines .detrend_none, .detrend_mean, and .detrend_linear, but you can use a custom function as well. You can also use a string to choose one of the functions: ‘none’ calls .detrend_none. ‘mean’ calls .detrend_mean. ‘linear’ calls .detrend_linear.scale_by_freq (bool, default: True) – Whether the resulting density values should be scaled by the scaling frequency, which gives density in units of 1/Hz. This allows for integration over the returned frequency values. The default is True for MATLAB compatibility.
mode ({'default', 'psd', 'magnitude', 'angle', 'phase'}) – What sort of spectrum to use. Default is ‘psd’, which takes the power spectral density. ‘magnitude’ returns the magnitude spectrum. ‘angle’ returns the phase spectrum without unwrapping. ‘phase’ returns the phase spectrum with unwrapping.
noverlap (int, default: 128) – The number of points of overlap between blocks.
scale ({'default', 'linear', 'dB'}) – The scaling of the values in the spec. ‘linear’ is no scaling. ‘dB’ returns the values in dB scale. When mode is ‘psd’, this is dB power (10 * log10). Otherwise, this is dB amplitude (20 * log10). ‘default’ is ‘dB’ if mode is ‘psd’ or ‘magnitude’ and ‘linear’ otherwise. This must be ‘linear’ if mode is ‘angle’ or ‘phase’.
Fc (int, default: 0) – The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.
cmap (.Colormap, default:
rcParams[“image.cmap”](default:'viridis'))xextent (None or (xmin, xmax)) – The image extent along the x-axis. The default sets xmin to the left border of the first bin (spectrum column) and xmax to the right border of the last bin. Note that for noverlap>0 the width of the bins is smaller than those of the segments.
data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x
vmin (float, optional) – vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the data.
vmax (float, optional) – vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the data.
**kwargs – Additional keyword arguments are passed on to ~.axes.Axes.imshow which makes the specgram image. The origin keyword argument is not supported.
- Return type:
- Returns:
spectrum (2D array) – Columns are the periodograms of successive segments.
freqs (1-D array) – The frequencies corresponding to the rows in spectrum.
t (1-D array) – The times corresponding to midpoints of segments (i.e., the columns in spectrum).
im (.AxesImage) – The image created by imshow containing the spectrogram.
See also
psdDiffers in the default overlap; in returning the mean of the segment periodograms; in not returning times; and in generating a line plot instead of colormap.
magnitude_spectrumA single spectrum, similar to having a single segment when mode is ‘magnitude’. Plots a line instead of a colormap.
angle_spectrumA single spectrum, similar to having a single segment when mode is ‘angle’. Plots a line instead of a colormap.
phase_spectrumA single spectrum, similar to having a single segment when mode is ‘phase’. Plots a line instead of a colormap.
Notes
Note
This is the pyplot wrapper for .axes.Axes.specgram.
The parameters detrend and scale_by_freq do only apply when mode is set to ‘psd’.
- scitex.plt.psd(x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None, return_line=None, *, data=None, **kwargs)[source]
Plot the power spectral density.
The power spectral density \(P_{xx}\) by Welch’s average periodogram method. The vector x is divided into NFFT length segments. Each segment is detrended by function detrend and windowed by function window. noverlap gives the length of the overlap between segments. The \(|\mathrm{fft}(i)|^2\) of each segment \(i\) are averaged to compute \(P_{xx}\), with a scaling to correct for power loss due to windowing.
If len(x) < NFFT, it will be zero padded to NFFT.
- Parameters:
x (1-D array or sequence) – Array or sequence containing the data
Fs (float, default: 2) – The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.
window (callable or ndarray, default: .window_hanning) – A function or a vector of length NFFT. To create window vectors see .window_hanning, .window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.
sides ({'default', 'onesided', 'twosided'}, optional) – Which sides of the spectrum to return. ‘default’ is one-sided for real data and two-sided for complex data. ‘onesided’ forces the return of a one-sided spectrum, while ‘twosided’ forces two-sided.
pad_to (int, optional) – The number of points to which the data segment is padded when performing the FFT. This can be different from NFFT, which specifies the number of data points used. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to ~numpy.fft.fft. The default is None, which sets pad_to equal to NFFT
NFFT (int, default: 256) – The number of data points used in each block for the FFT. A power 2 is most efficient. This should NOT be used to get zero padding, or the scaling of the result will be incorrect; use pad_to for this instead.
detrend ({'none', 'mean', 'linear'} or callable, default: 'none') – The function applied to each segment before fft-ing, designed to remove the mean or linear trend. Unlike in MATLAB, where the detrend parameter is a vector, in Matplotlib it is a function. The
mlabmodule defines .detrend_none, .detrend_mean, and .detrend_linear, but you can use a custom function as well. You can also use a string to choose one of the functions: ‘none’ calls .detrend_none. ‘mean’ calls .detrend_mean. ‘linear’ calls .detrend_linear.scale_by_freq (bool, default: True) – Whether the resulting density values should be scaled by the scaling frequency, which gives density in units of 1/Hz. This allows for integration over the returned frequency values. The default is True for MATLAB compatibility.
noverlap (int, default: 0 (no overlap)) – The number of points of overlap between segments.
Fc (int, default: 0) – The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.
return_line (bool, default: False) – Whether to include the line object plotted in the returned values.
data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x
**kwargs –
Keyword arguments control the .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 and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color 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: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: color or 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] mouseover: bool path_effects: list of .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: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float
- Return type:
- Returns:
Pxx (1-D array) – The values for the power spectrum \(P_{xx}\) before scaling (real valued).
freqs (1-D array) – The frequencies corresponding to the elements in Pxx.
line (~matplotlib.lines.Line2D) – The line created by this function. Only returned if return_line is True.
See also
specgramDiffers in the default overlap; in not returning the mean of the segment periodograms; in returning the times of the segments; and in plotting a colormap instead of a line.
magnitude_spectrumPlots the magnitude spectrum.
csdPlots the spectral density between two signals.
Notes
Note
This is the pyplot wrapper for .axes.Axes.psd.
For plotting, the power is plotted as \(10\log_{10}(P_{xx})\) for decibels, though Pxx itself is returned.
References
Bendat & Piersol – Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986)
- scitex.plt.csd(x, y, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None, return_line=None, *, data=None, **kwargs)[source]
Plot the cross-spectral density.
The cross spectral density \(P_{xy}\) by Welch’s average periodogram method. The vectors x and y are divided into NFFT length segments. Each segment is detrended by function detrend and windowed by function window. noverlap gives the length of the overlap between segments. The product of the direct FFTs of x and y are averaged over each segment to compute \(P_{xy}\), with a scaling to correct for power loss due to windowing.
If len(x) < NFFT or len(y) < NFFT, they will be zero padded to NFFT.
- Parameters:
x (1-D arrays or sequences) – Arrays or sequences containing the data.
y (1-D arrays or sequences) – Arrays or sequences containing the data.
Fs (float, default: 2) – The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.
window (callable or ndarray, default: .window_hanning) – A function or a vector of length NFFT. To create window vectors see .window_hanning, .window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.
sides ({'default', 'onesided', 'twosided'}, optional) – Which sides of the spectrum to return. ‘default’ is one-sided for real data and two-sided for complex data. ‘onesided’ forces the return of a one-sided spectrum, while ‘twosided’ forces two-sided.
pad_to (int, optional) – The number of points to which the data segment is padded when performing the FFT. This can be different from NFFT, which specifies the number of data points used. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to ~numpy.fft.fft. The default is None, which sets pad_to equal to NFFT
NFFT (int, default: 256) – The number of data points used in each block for the FFT. A power 2 is most efficient. This should NOT be used to get zero padding, or the scaling of the result will be incorrect; use pad_to for this instead.
detrend ({'none', 'mean', 'linear'} or callable, default: 'none') – The function applied to each segment before fft-ing, designed to remove the mean or linear trend. Unlike in MATLAB, where the detrend parameter is a vector, in Matplotlib it is a function. The
mlabmodule defines .detrend_none, .detrend_mean, and .detrend_linear, but you can use a custom function as well. You can also use a string to choose one of the functions: ‘none’ calls .detrend_none. ‘mean’ calls .detrend_mean. ‘linear’ calls .detrend_linear.scale_by_freq (bool, default: True) – Whether the resulting density values should be scaled by the scaling frequency, which gives density in units of 1/Hz. This allows for integration over the returned frequency values. The default is True for MATLAB compatibility.
noverlap (int, default: 0 (no overlap)) – The number of points of overlap between segments.
Fc (int, default: 0) – The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.
return_line (bool, default: False) – Whether to include the line object plotted in the returned values.
data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x, y
**kwargs –
Keyword arguments control the .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 and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color 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: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: color or 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] mouseover: bool path_effects: list of .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: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float
- Return type:
- Returns:
Pxy (1-D array) – The values for the cross spectrum \(P_{xy}\) before scaling (complex valued).
freqs (1-D array) – The frequencies corresponding to the elements in Pxy.
line (~matplotlib.lines.Line2D) – The line created by this function. Only returned if return_line is True.
See also
psdis equivalent to setting
y = x.
Notes
Note
This is the pyplot wrapper for .axes.Axes.csd.
For plotting, the power is plotted as \(10 \log_{10}(P_{xy})\) for decibels, though \(P_{xy}\) itself is returned.
References
Bendat & Piersol – Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986)
- scitex.plt.cohere(x, y, NFFT=256, Fs=2, Fc=0, detrend=<function detrend_none>, window=<function window_hanning>, noverlap=0, pad_to=None, sides='default', scale_by_freq=None, *, data=None, **kwargs)[source]
Plot the coherence between x and y.
Coherence is the normalized cross spectral density:
\[C_{xy} = \frac{|P_{xy}|^2}{P_{xx}P_{yy}}\]- Parameters:
Fs (float, default: 2) – The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.
window (callable or ndarray, default: .window_hanning) – A function or a vector of length NFFT. To create window vectors see .window_hanning, .window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.
sides ({'default', 'onesided', 'twosided'}, optional) – Which sides of the spectrum to return. ‘default’ is one-sided for real data and two-sided for complex data. ‘onesided’ forces the return of a one-sided spectrum, while ‘twosided’ forces two-sided.
pad_to (int, optional) – The number of points to which the data segment is padded when performing the FFT. This can be different from NFFT, which specifies the number of data points used. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to ~numpy.fft.fft. The default is None, which sets pad_to equal to NFFT
NFFT (int, default: 256) – The number of data points used in each block for the FFT. A power 2 is most efficient. This should NOT be used to get zero padding, or the scaling of the result will be incorrect; use pad_to for this instead.
detrend ({'none', 'mean', 'linear'} or callable, default: 'none') – The function applied to each segment before fft-ing, designed to remove the mean or linear trend. Unlike in MATLAB, where the detrend parameter is a vector, in Matplotlib it is a function. The
mlabmodule defines .detrend_none, .detrend_mean, and .detrend_linear, but you can use a custom function as well. You can also use a string to choose one of the functions: ‘none’ calls .detrend_none. ‘mean’ calls .detrend_mean. ‘linear’ calls .detrend_linear.scale_by_freq (bool, default: True) – Whether the resulting density values should be scaled by the scaling frequency, which gives density in units of 1/Hz. This allows for integration over the returned frequency values. The default is True for MATLAB compatibility.
noverlap (int, default: 0 (no overlap)) – The number of points of overlap between blocks.
Fc (int, default: 0) – The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.
data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x, y
**kwargs –
Keyword arguments control the .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 and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color 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: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: color or 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] mouseover: bool path_effects: list of .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: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float
- Return type:
- Returns:
Cxy (1-D array) – The coherence vector.
freqs (1-D array) – The frequencies for the elements in Cxy.
Notes
Note
This is the pyplot wrapper for .axes.Axes.cohere.
References
Bendat & Piersol – Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986)
- scitex.plt.magnitude_spectrum(x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, scale=None, *, data=None, **kwargs)[source]
Plot the magnitude spectrum.
Compute the magnitude spectrum of x. Data is padded to a length of pad_to and the windowing function window is applied to the signal.
- Parameters:
x (1-D array or sequence) – Array or sequence containing the data.
Fs (float, default: 2) – The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.
window (callable or ndarray, default: .window_hanning) – A function or a vector of length NFFT. To create window vectors see .window_hanning, .window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.
sides ({'default', 'onesided', 'twosided'}, optional) – Which sides of the spectrum to return. ‘default’ is one-sided for real data and two-sided for complex data. ‘onesided’ forces the return of a one-sided spectrum, while ‘twosided’ forces two-sided.
pad_to (int, optional) – The number of points to which the data segment is padded when performing the FFT. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to ~numpy.fft.fft. The default is None, which sets pad_to equal to the length of the input signal (i.e. no padding).
scale ({'default', 'linear', 'dB'}) – The scaling of the values in the spec. ‘linear’ is no scaling. ‘dB’ returns the values in dB scale, i.e., the dB amplitude (20 * log10). ‘default’ is ‘linear’.
Fc (int, default: 0) – The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.
data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x
**kwargs –
Keyword arguments control the .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 and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color 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: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: color or 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] mouseover: bool path_effects: list of .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: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float
- Return type:
- Returns:
spectrum (1-D array) – The values for the magnitude spectrum before scaling (real valued).
freqs (1-D array) – The frequencies corresponding to the elements in spectrum.
line (~matplotlib.lines.Line2D) – The line created by this function.
See also
psdPlots the power spectral density.
angle_spectrumPlots the angles of the corresponding frequencies.
phase_spectrumPlots the phase (unwrapped angle) of the corresponding frequencies.
specgramCan plot the magnitude spectrum of segments within the signal in a colormap.
Notes
Note
This is the pyplot wrapper for .axes.Axes.magnitude_spectrum.
- scitex.plt.angle_spectrum(x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, *, data=None, **kwargs)[source]
Plot the angle spectrum.
Compute the angle spectrum (wrapped phase spectrum) of x. Data is padded to a length of pad_to and the windowing function window is applied to the signal.
- Parameters:
x (1-D array or sequence) – Array or sequence containing the data.
Fs (float, default: 2) – The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.
window (callable or ndarray, default: .window_hanning) – A function or a vector of length NFFT. To create window vectors see .window_hanning, .window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.
sides ({'default', 'onesided', 'twosided'}, optional) – Which sides of the spectrum to return. ‘default’ is one-sided for real data and two-sided for complex data. ‘onesided’ forces the return of a one-sided spectrum, while ‘twosided’ forces two-sided.
pad_to (int, optional) – The number of points to which the data segment is padded when performing the FFT. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to ~numpy.fft.fft. The default is None, which sets pad_to equal to the length of the input signal (i.e. no padding).
Fc (int, default: 0) – The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.
data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x
**kwargs –
Keyword arguments control the .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 and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color 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: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: color or 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] mouseover: bool path_effects: list of .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: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float
- Return type:
- Returns:
spectrum (1-D array) – The values for the angle spectrum in radians (real valued).
freqs (1-D array) – The frequencies corresponding to the elements in spectrum.
line (~matplotlib.lines.Line2D) – The line created by this function.
See also
magnitude_spectrumPlots the magnitudes of the corresponding frequencies.
phase_spectrumPlots the unwrapped version of this function.
specgramCan plot the angle spectrum of segments within the signal in a colormap.
Notes
Note
This is the pyplot wrapper for .axes.Axes.angle_spectrum.
- scitex.plt.phase_spectrum(x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, *, data=None, **kwargs)[source]
Plot the phase spectrum.
Compute the phase spectrum (unwrapped angle spectrum) of x. Data is padded to a length of pad_to and the windowing function window is applied to the signal.
- Parameters:
x (1-D array or sequence) – Array or sequence containing the data
Fs (float, default: 2) – The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.
window (callable or ndarray, default: .window_hanning) – A function or a vector of length NFFT. To create window vectors see .window_hanning, .window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.
sides ({'default', 'onesided', 'twosided'}, optional) – Which sides of the spectrum to return. ‘default’ is one-sided for real data and two-sided for complex data. ‘onesided’ forces the return of a one-sided spectrum, while ‘twosided’ forces two-sided.
pad_to (int, optional) – The number of points to which the data segment is padded when performing the FFT. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to ~numpy.fft.fft. The default is None, which sets pad_to equal to the length of the input signal (i.e. no padding).
Fc (int, default: 0) – The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.
data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x
**kwargs –
Keyword arguments control the .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 and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color 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: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: color or 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] mouseover: bool path_effects: list of .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: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float
- Return type:
- Returns:
spectrum (1-D array) – The values for the phase spectrum in radians (real valued).
freqs (1-D array) – The frequencies corresponding to the elements in spectrum.
line (~matplotlib.lines.Line2D) – The line created by this function.
See also
magnitude_spectrumPlots the magnitudes of the corresponding frequencies.
angle_spectrumPlots the wrapped version of this function.
specgramCan plot the phase spectrum of segments within the signal in a colormap.
Notes
Note
This is the pyplot wrapper for .axes.Axes.phase_spectrum.
- scitex.plt.xcorr(x, y, normed=True, detrend=<function detrend_none>, usevlines=True, maxlags=10, *, data=None, **kwargs)[source]
Plot the cross correlation between x and y.
The correlation with lag k is defined as \(\sum_n x[n+k] \cdot y^*[n]\), where \(y^*\) is the complex conjugate of \(y\).
- Parameters:
x (array-like of length n) – Neither x nor y are run through Matplotlib’s unit conversion, so these should be unit-less arrays.
y (array-like of length n) – Neither x nor y are run through Matplotlib’s unit conversion, so these should be unit-less arrays.
detrend (callable, default: .mlab.detrend_none (no detrending)) –
A detrending function applied to x and y. It must have the signature
detrend(x: np.ndarray) -> np.ndarray
normed (bool, default: True) – If
True, input vectors are normalised to unit length.usevlines (bool, default: True) –
Determines the plot style.
If
True, vertical lines are plotted from 0 to the xcorr value using .Axes.vlines. Additionally, a horizontal line is plotted at y=0 using .Axes.axhline.If
False, markers are plotted at the xcorr values using .Axes.plot.maxlags (int, default: 10) – Number of lags to show. If None, will return all
2 * len(x) - 1lags.linestyle (~matplotlib.lines.Line2D property, optional) – The linestyle for plotting the data points. Only used if usevlines is
False.marker (str, default: 'o') – The marker for plotting the data points. Only used if usevlines is
False.data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x, y
**kwargs – Additional parameters are passed to .Axes.vlines and .Axes.axhline if usevlines is
True; otherwise they are passed to .Axes.plot.
- Return type:
tuple[ndarray,ndarray,LineCollection|Line2D,Line2D|None]- Returns:
lags (array (length
2*maxlags+1)) – The lag vector.c (array (length
2*maxlags+1)) – The auto correlation vector.line (.LineCollection or .Line2D) – .Artist added to the Axes of the correlation:
.LineCollection if usevlines is True.
.Line2D if usevlines is False.
b (~matplotlib.lines.Line2D or None) – Horizontal line at 0 if usevlines is True None usevlines is False.
Notes
Note
This is the pyplot wrapper for .axes.Axes.xcorr.
The cross correlation is performed with numpy.correlate with
mode = "full".
- scitex.plt.acorr(x, *, data=None, **kwargs)[source]
Plot the autocorrelation of x.
- Parameters:
x (array-like) – Not run through Matplotlib’s unit conversion, so this should be a unit-less array.
detrend (callable, default: .mlab.detrend_none (no detrending)) –
A detrending function applied to x. It must have the signature
detrend(x: np.ndarray) -> np.ndarray
normed (bool, default: True) – If
True, input vectors are normalised to unit length.usevlines (bool, default: True) –
Determines the plot style.
If
True, vertical lines are plotted from 0 to the acorr value using .Axes.vlines. Additionally, a horizontal line is plotted at y=0 using .Axes.axhline.If
False, markers are plotted at the acorr values using .Axes.plot.maxlags (int, default: 10) – Number of lags to show. If
None, will return all2 * len(x) - 1lags.linestyle (~matplotlib.lines.Line2D property, optional) – The linestyle for plotting the data points. Only used if usevlines is
False.marker (str, default: 'o') – The marker for plotting the data points. Only used if usevlines is
False.data (indexable object, optional) –
If given, the following parameters also accept a string
s, which is interpreted asdata[s]ifsis a key indata:x
**kwargs – Additional parameters are passed to .Axes.vlines and .Axes.axhline if usevlines is
True; otherwise they are passed to .Axes.plot.
- Return type:
tuple[ndarray,ndarray,LineCollection|Line2D,Line2D|None]- Returns:
lags (array (length
2*maxlags+1)) – The lag vector.c (array (length
2*maxlags+1)) – The auto correlation vector.line (.LineCollection or .Line2D) – .Artist added to the Axes of the correlation:
.LineCollection if usevlines is True.
.Line2D if usevlines is False.
b (~matplotlib.lines.Line2D or None) – Horizontal line at 0 if usevlines is True None usevlines is False.
Notes
Note
This is the pyplot wrapper for .axes.Axes.acorr.
The cross correlation is performed with numpy.correlate with
mode = "full".
- scitex.plt.semilogy(*args, **kwargs)[source]
Make a plot with log scaling on the y-axis.
Call signatures:
semilogy([x], y, [fmt], data=None, **kwargs) semilogy([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
This is just a thin wrapper around .plot which additionally changes the y-axis to log scaling. All the concepts and parameters of plot can be used here as well.
The additional parameters base, subs, and nonpositive control the y-axis properties. They are just forwarded to .Axes.set_yscale.
- Parameters:
base (float, default: 10) – Base of the y logarithm.
subs (array-like, optional) – The location of the minor yticks. If None, reasonable locations are automatically chosen depending on the number of decades in the plot. See .Axes.set_yscale for details.
nonpositive ({'mask', 'clip'}, default: 'clip') – Non-positive values in y can be masked as invalid, or clipped to a very small positive number.
**kwargs – All parameters supported by .plot.
- Returns:
Objects representing the plotted data.
- Return type:
list of .Line2D
Notes
Note
This is the pyplot wrapper for .axes.Axes.semilogy.
- scitex.plt.semilogx(*args, **kwargs)[source]
Make a plot with log scaling on the x-axis.
Call signatures:
semilogx([x], y, [fmt], data=None, **kwargs) semilogx([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
This is just a thin wrapper around .plot which additionally changes the x-axis to log scaling. All the concepts and parameters of plot can be used here as well.
The additional parameters base, subs, and nonpositive control the x-axis properties. They are just forwarded to .Axes.set_xscale.
- Parameters:
base (float, default: 10) – Base of the x logarithm.
subs (array-like, optional) – The location of the minor xticks. If None, reasonable locations are automatically chosen depending on the number of decades in the plot. See .Axes.set_xscale for details.
nonpositive ({'mask', 'clip'}, default: 'clip') – Non-positive values in x can be masked as invalid, or clipped to a very small positive number.
**kwargs – All parameters supported by .plot.
- Returns:
Objects representing the plotted data.
- Return type:
list of .Line2D
Notes
Note
This is the pyplot wrapper for .axes.Axes.semilogx.
- scitex.plt.loglog(*args, **kwargs)[source]
Make a plot with log scaling on both the x- and y-axis.
Call signatures:
loglog([x], y, [fmt], data=None, **kwargs) loglog([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
This is just a thin wrapper around .plot which additionally changes both the x-axis and the y-axis to log scaling. All the concepts and parameters of plot can be used here as well.
The additional parameters base, subs and nonpositive control the x/y-axis properties. They are just forwarded to .Axes.set_xscale and .Axes.set_yscale. To use different properties on the x-axis and the y-axis, use e.g.
ax.set_xscale("log", base=10); ax.set_yscale("log", base=2).- Parameters:
base (float, default: 10) – Base of the logarithm.
subs (sequence, optional) – The location of the minor ticks. If None, reasonable locations are automatically chosen depending on the number of decades in the plot. See .Axes.set_xscale/.Axes.set_yscale for details.
nonpositive ({'mask', 'clip'}, default: 'clip') – Non-positive values can be masked as invalid, or clipped to a very small positive number.
**kwargs – All parameters supported by .plot.
- Returns:
Objects representing the plotted data.
- Return type:
list of .Line2D
Notes
Note
This is the pyplot wrapper for .axes.Axes.loglog.
- scitex.plt.polar(*args, **kwargs)[source]
Make a polar plot.
call signature:
polar(theta, r, [fmt], **kwargs)
This is a convenience wrapper around .pyplot.plot. It ensures that the current Axes is polar (or creates one if needed) and then passes all parameters to
.pyplot.plot.Note
When making polar plots using the pyplot API,
polar()should typically be the first command because that makes sure a polar Axes is created. Using other commands such asplt.title()before this can lead to the implicit creation of a rectangular Axes, in which case a subsequentpolar()call will fail.
- scitex.plt.rc(group, **kwargs)[source]
Set the current .rcParams. group is the grouping for the rc, e.g., for
lines.linewidththe group islines, foraxes.facecolor, the group isaxes, and so on. Group may also be a list or tuple of group names, e.g., (xtick, ytick). kwargs is a dictionary attribute name/value pairs, e.g.,:rc('lines', linewidth=2, color='r')
sets the current .rcParams and is equivalent to:
rcParams['lines.linewidth'] = 2 rcParams['lines.color'] = 'r'
The following aliases are available to save typing for interactive users:
Alias
Property
‘lw’
‘linewidth’
‘ls’
‘linestyle’
‘c’
‘color’
‘fc’
‘facecolor’
‘ec’
‘edgecolor’
‘mew’
‘markeredgewidth’
‘aa’
‘antialiased’
Thus you could abbreviate the above call as:
rc('lines', lw=2, c='r')
Note you can use python’s kwargs dictionary facility to store dictionaries of default parameters. e.g., you can customize the font rc as follows:
font = {'family' : 'monospace', 'weight' : 'bold', 'size' : 'larger'} rc('font', **font) # pass in the font dict as kwargs
This enables you to easily switch between several configurations. Use
matplotlib.style.use('default')orrcdefaults()to restore the default .rcParams after changes.Notes
Note
This is equivalent to matplotlib.rc.
Similar functionality is available by using the normal dict interface, i.e.
rcParams.update({"lines.linewidth": 2, ...})(butrcParams.updatedoes not support abbreviations or grouping).- Return type:
- scitex.plt.rcdefaults()[source]
Restore the .rcParams from Matplotlib’s internal default style.
Style-blacklisted .rcParams (defined in
matplotlib.style.core.STYLE_BLACKLIST) are not updated.See also
matplotlib.rc_file_defaultsRestore the .rcParams from the rc file originally loaded by Matplotlib.
matplotlib.style.useUse a specific style file. Call
style.use('default')to restore the default style.
Notes
Note
This is equivalent to matplotlib.rcdefaults.
- Return type:
- scitex.plt.get_cmap(name=None, lut=None)[source]
Get a colormap instance, defaulting to rc values if name is None.
- Parameters:
name (~matplotlib.colors.Colormap or str or None, default: None) – If a .Colormap instance, it will be returned. Otherwise, the name of a colormap known to Matplotlib, which will be resampled by lut. The default, None, means
rcParams[“image.cmap”](default:'viridis').lut (int or None, default: None) – If name is not already a Colormap instance and lut is not None, the colormap will be resampled to have lut entries in the lookup table.
- Return type:
Colormap
- scitex.plt.build_spec(params)[source]
Convert a parameter dict to a figrecipe spec dict.
- Parameters:
params (dict) – Flat parameter dict. Required key:
kind. For XY plots:x,y(comma-separated floats or strings). For distributions:data,data2..data6,labels. For pie:data,labels. For heatmap:data,nrows,ncols. Optional:color,title,xlabel,ylabel,width,height,yerr.- Returns:
Figrecipe-compatible spec.
- Return type:
- Raises:
ValueError – If required parameters are missing or kind is unsupported.
- scitex.plt.build_spec_from_csv(csv_path, params)[source]
Build a figrecipe spec from a CSV file path and parameters.
Uses figrecipe’s native
data_file+ column name resolution.- Parameters:
- Returns:
Figrecipe-compatible spec.
- Return type:
- Raises:
ValueError – If required parameters are missing or kind is unsupported.
- scitex.plt.render_spec_to_bytes(spec, *, dpi=300, fmt='png', facecolor='white')[source]
Render a figrecipe spec dict to image bytes.
- Parameters:
- Returns:
Encoded image bytes.
- Return type:
- scitex.plt.termplot(*args)[source]
Plot y (and optional x) values in the terminal using termplotlib.
- Parameters:
*args – Either
(y,)— plotted against its indices — or(x, y, ...)where extra positional arguments are ignored.- Returns:
Displays the plot in the terminal.
- Return type:
None
- scitex.plt.draw_graph(ax, G, *, layout='spring', pos=None, seed=42, node_size=100, node_color='#3498db', node_alpha=0.8, node_shape='o', node_edgecolors='white', node_linewidths=0.34, edge_width=0.34, edge_color='gray', edge_alpha=0.5, edge_style='solid', arrows=None, arrowsize=10, arrowstyle='-|>', connectionstyle='arc3,rad=0.0', labels=False, font_size=6, font_color='black', font_weight='normal', font_family='sans-serif', colormap='viridis', vmin=None, vmax=None, **layout_kwargs)[source]
Draw a NetworkX graph on matplotlib axes.
- Parameters:
ax (matplotlib.axes.Axes) – The axes to draw on.
G (networkx.Graph) – The graph to draw.
layout (str) – Layout algorithm: ‘spring’, ‘circular’, ‘kamada_kawai’, ‘shell’, ‘spectral’, ‘random’, ‘planar’, ‘spiral’, ‘hierarchical’.
pos (dict, optional) – Pre-computed node positions {node: (x, y)}.
seed (int) – Random seed for layout reproducibility.
node_size (str, callable, or float) – Node sizes. Can be attribute name, callable (node, data) -> size, or scalar.
node_color (str, callable, or any) – Node colors. Can be attribute name, callable, color name, or array.
node_alpha (float) – Node transparency.
node_shape (str) – Node marker shape.
edge_width (str, callable, or float) – Edge widths. Can be attribute name, callable (u, v, data) -> width, or scalar.
edge_color (str, callable, or any) – Edge colors.
edge_alpha (float) – Edge transparency.
arrows (bool, optional) – Draw arrows for directed graphs. Auto-detected if None.
arrowsize (float) – Arrow head size for directed edges.
labels (bool, dict, or str) – Node labels. True for node IDs, dict for custom labels, str for attribute name.
font_size (float) – Label font size (default 6pt for scitex).
colormap (str) – Matplotlib colormap for numeric node colors.
**layout_kwargs – Additional kwargs passed to layout algorithm.
- Returns:
Dictionary with ‘pos’, ‘node_collection’, ‘edge_collection’.
- Return type:
- scitex.plt.smart_align(fig, panels=None)
Automatically align panels in a compact grid layout.
Works like human behavior: 1. Detect grid structure (nrows, ncols) 2. Place panels from top-left to bottom-right 3. Calculate minimum rectangle to cover all content in each row/column 4. Unify row heights and column widths 5. Use space effectively with theme margins and spacing
Uses margin and spacing values from the loaded SCITEX theme: - margins.left_mm, margins.right_mm, margins.top_mm, margins.bottom_mm - spacing.horizontal_mm, spacing.vertical_mm
- Parameters:
- Return type:
Examples
>>> import figrecipe as fr >>> fig, axes = fr.subplots(2, 2) >>> # ... add plots ... >>> fr.align_smart(fig) # Align all panels using theme settings
- scitex.plt.align_smart(fig, panels=None)[source]
Automatically align panels in a compact grid layout.
Works like human behavior: 1. Detect grid structure (nrows, ncols) 2. Place panels from top-left to bottom-right 3. Calculate minimum rectangle to cover all content in each row/column 4. Unify row heights and column widths 5. Use space effectively with theme margins and spacing
Uses margin and spacing values from the loaded SCITEX theme: - margins.left_mm, margins.right_mm, margins.top_mm, margins.bottom_mm - spacing.horizontal_mm, spacing.vertical_mm
- Parameters:
- Return type:
Examples
>>> import figrecipe as fr >>> fig, axes = fr.subplots(2, 2) >>> # ... add plots ... >>> fr.align_smart(fig) # Align all panels using theme settings
- scitex.plt.enable_svg()[source]
Manually enable SVG format for Jupyter notebook display.
Call this if figures appear pixelated in notebooks.
Examples
>>> import figrecipe as fr >>> fr.enable_svg() # Enable SVG rendering >>> fig, ax = fr.subplots() # Now renders as crisp SVG
- scitex.plt.edit(source=None, style=None, port=5050, host='127.0.0.1', open_browser=True, hot_reload=False, working_dir=None, desktop=False)
Launch interactive GUI editor for figure styling.
- Parameters:
source (RecordingFigure, str, Path, or None) – Either a live RecordingFigure object, path to a .yaml recipe file, or None to create a new blank figure.
style (str or dict, optional) – Style preset name or style dict.
port (int, optional) – Django server port (default: 5050).
host (str, optional) – Host to bind server (default: “127.0.0.1”, use “0.0.0.0” for Docker).
open_browser (bool, optional) – Whether to open browser automatically (default: True).
hot_reload (bool, optional) – Enable hot reload (default: False).
working_dir (str or Path, optional) – Working directory for file browser (default: directory containing source).
desktop (bool, optional) – Launch as native desktop window using pywebview (default: False). Requires: pip install figrecipe[desktop]
- Returns:
Final style overrides after editing session.
- Return type:
- scitex.plt.gui(source=None, style=None, port=5050, host='127.0.0.1', open_browser=True, hot_reload=False, working_dir=None, desktop=False)[source]
Launch interactive GUI editor for figure styling.
- Parameters:
source (RecordingFigure, str, Path, or None) – Either a live RecordingFigure object, path to a .yaml recipe file, or None to create a new blank figure.
style (str or dict, optional) – Style preset name or style dict.
port (int, optional) – Django server port (default: 5050).
host (str, optional) – Host to bind server (default: “127.0.0.1”, use “0.0.0.0” for Docker).
open_browser (bool, optional) – Whether to open browser automatically (default: True).
hot_reload (bool, optional) – Enable hot reload (default: False).
working_dir (str or Path, optional) – Working directory for file browser (default: directory containing source).
desktop (bool, optional) – Launch as native desktop window using pywebview (default: False). Requires: pip install figrecipe[desktop]
- Returns:
Final style overrides after editing session.
- Return type:
- scitex.plt.apply_style(ax, style=None)[source]
Apply mm-based styling to an axes.
- Parameters:
ax (matplotlib.axes.Axes) – Target axes to apply styling to.
style (dict or DotDict, optional) – Style configuration. If None, uses default FIGRECIPE_STYLE.
- Returns:
Trace line width in points.
- Return type:
Examples
>>> import figrecipe as ps >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots() >>> trace_lw = ps.apply_style(ax) >>> ax.plot(x, y, lw=trace_lw)
- scitex.plt.load_style(style='SCITEX', dark=False, background=None)[source]
Load style configuration and apply it globally.
After calling this function, subsequent subplots() calls will automatically use the loaded style (fonts, colors, theme, etc.).
- Parameters:
style (str, Path, bool, or None) – One of: - “SCITEX” / “FIGRECIPE”: Scientific publication style (default) - “MATPLOTLIB”: Vanilla matplotlib defaults - Path to custom YAML file: “/path/to/my_style.yaml” - None or False: Unload style (reset to matplotlib defaults)
dark (bool, optional) – If True, apply dark theme transformation (default: False). Equivalent to appending “_DARK” to preset name.
background (str, optional) – Override default background color. E.g., ‘white’ for opaque figures. Sets theme.light.figure_bg and theme.light.axes_bg. Use ‘transparent’ for transparent background.
- Returns:
Style configuration with dot-notation access. Returns None if style is unloaded.
- Return type:
DotDict or None
Examples
>>> import figrecipe as fr
>>> # Load scientific style (default) >>> fr.load_style() >>> fr.load_style("SCITEX") # explicit
>>> # Load with white background (override transparent default) >>> fr.load_style("SCITEX", background='white')
>>> # Load dark theme >>> fr.load_style("SCITEX_DARK") >>> fr.load_style("SCITEX", dark=True) # equivalent
>>> # Reset to vanilla matplotlib >>> fr.load_style(None) # unload >>> fr.load_style(False) # unload >>> fr.load_style("MATPLOTLIB") # explicit vanilla
>>> # Access style values >>> style = fr.load_style("SCITEX") >>> style.axes.width_mm 40
- scitex.plt.unload_style()[source]
Unload the current style and reset to matplotlib defaults.
After calling this, subsequent subplots() calls will use vanilla matplotlib behavior without FigRecipe styling.
Examples
>>> import figrecipe as fr >>> fr.load_style("SCITEX") # Apply scientific style >>> fig, ax = fr.subplots() # Styled >>> fr.unload_style() # Reset to matplotlib defaults >>> fig, ax = fr.subplots() # Vanilla matplotlib
- scitex.plt.list_presets()[source]
List available style presets.
Examples
>>> import figrecipe as ps >>> ps.list_presets() ['MINIMAL', 'PRESENTATION', 'SCIENTIFIC']
- scitex.plt.compose(sources, layout=None, canvas_size_mm=None, gap_mm=5.0, dpi=300, panel_labels=False, label_style='uppercase', **kwargs)[source]
Compose a new figure from multiple sources (recipes or raw images).
Supports two modes automatically detected from sources format:
Grid-based: sources={(row, col): path} Uses layout=(nrows, ncols) for subplot grid.
Mm-based: sources={path: {“xy_mm”: (x, y), “size_mm”: (w, h)}} Uses canvas_size_mm for precise positioning.
- Parameters:
sources (dict) – Either: - Grid-based: {(row, col): source_path} mapping positions to sources - Mm-based: {source_path: {“xy_mm”: (x, y), “size_mm”: (w, h)}}
layout (tuple, optional) – (nrows, ncols) for grid-based composition. Auto-detected if not provided.
canvas_size_mm (tuple, optional) – (width_mm, height_mm) for mm-based composition. Required for mm-based mode.
gap_mm (float) – Gap between panels in mm (for auto-layout modes like ‘horizontal’).
dpi (int) – DPI for the output figure.
panel_labels (bool) – If True, add panel labels (A, B, C…) to each panel.
label_style (str) – ‘uppercase’, ‘lowercase’, or ‘numeric’.
**kwargs – Additional arguments passed to figure creation.
- Return type:
Tuple[RecordingFigure,Union[RecordingAxes,ndarray[tuple[Any,...],dtype[TypeVar(_ScalarT, bound=generic)]],List[RecordingAxes]]]- Returns:
fig (RecordingFigure) – Composed figure (editable, recordable).
axes (RecordingAxes, ndarray, or list) – Axes of the composed figure.
Examples
Grid-based composition:
>>> fig, axes = fr.compose( ... layout=(1, 2), ... sources={ ... (0, 0): "panel_a.yaml", ... (0, 1): "panel_b.yaml", ... } ... )
Mm-based free-form composition:
>>> fig, axes = fr.compose( ... canvas_size_mm=(180, 120), ... sources={ ... "panel_a.yaml": {"xy_mm": (0, 0), "size_mm": (85, 55)}, ... "panel_b.yaml": {"xy_mm": (90, 0), "size_mm": (85, 55)}, ... "panel_c.yaml": {"xy_mm": (0, 60), "size_mm": (175, 55)}, ... } ... )
- scitex.plt.crop(input_path, output_path=None, margin_mm=1.0, margin_px=None, overwrite=False, verbose=False, return_offset=False)[source]
Crop a figure image to its content area with a specified margin.
- Parameters:
input_path (str or Path) – Path to the input image.
output_path (str or Path, optional) – Path to save the cropped image.
margin_mm (float, optional) – Margin in millimeters (default: 1.0mm).
margin_px (int, optional) – Margin in pixels (overrides margin_mm if provided).
overwrite (bool, optional) – Whether to overwrite the input file (default: False)
verbose (bool, optional) – Whether to print detailed information (default: False)
return_offset (bool, optional) – If True, also return crop offset info dict (default: False)
- Returns:
Path to the saved cropped image. If return_offset=True, returns (path, offset_dict).
- Return type:
Path or tuple
- class scitex.plt.Diagram(title=None, width_mm=170.0, height_mm=120.0, padding_mm=10.0, gap_mm=None)[source]
Bases:
objectBuilder for rich box-and-arrow diagrams with mm-based coordinates.
- add_box(id, title, subtitle=None, content=None, emphasis='normal', shape='rounded', x_mm=None, y_mm=None, width_mm=None, height_mm=None, fill_color=None, border_color=None, title_color=None, padding_mm=5.0, margin_mm=0.0, node_class=None, state=None, language=None, bullet=None)[source]
Add a rich text box. See BoxSpec for node_class/state/language/bullet.
- Return type:
- add_container(id, title=None, children=None, emphasis='muted', x_mm=None, y_mm=None, width_mm=None, height_mm=None, fill_color=None, border_color=None, title_loc='upper center', direction='row', container_gap_mm=8.0, container_padding_mm=8.0, equalize_heights=True, equalize_widths=True)[source]
Add a container. equalize_heights/widths: match children in row/column.
- Return type:
- add_arrow(source, target, source_anchor='auto', target_anchor='auto', source_dx=0.0, source_dy=0.0, target_dx=0.0, target_dy=0.0, label=None, style='solid', color=None, curve=0.0, linewidth_mm=0.5, label_offset_mm=None, margin_mm=None)[source]
Add an arrow connecting two boxes.
- Return type:
- add_icon(id, source, x_mm, y_mm, width_mm=8.0, height_mm=8.0, color=None, opacity=1.0)[source]
Add an icon (SVG/PNG or built-in: warning/check/cross/info/lock).
- Return type:
- validate_containers()[source]
Check every container fully encloses its declared children.
- Return type:
- auto_layout(layout='lr', margin_mm=15.0, box_size_mm=None, gap_mm=10.0, avoid_overlap=True, justify='space-between', align_items='center')[source]
Automatically position boxes. See _layout for details.
- Return type:
- render(ax=None, auto_fix=False, auto_curve=True)[source]
Render. auto_fix=True resolves violations; auto_curve=False skips R7.
- save(path, dpi=200, save_recipe=True, save_hitmap=False, save_debug=True, watermark=False)[source]
Render, crop, and save. watermark=True adds ‘Plotted by scitex.ai’.
- Return type:
- render_to_file(path, dpi=200, save_recipe=True, save_hitmap=False, save_debug=True, watermark=False)
Render, crop, and save. watermark=True adds ‘Plotted by scitex.ai’.
- Return type:
- scitex.plt.align_panels(fig, panels, mode, reference=None)[source]
Align multiple panels to a reference panel.
- Parameters:
fig (RecordingFigure) – The figure containing the panels.
panels (list of tuple) – List of (row, col) positions to align.
mode (str or AlignmentMode) – Alignment mode: ‘left’, ‘right’, ‘top’, ‘bottom’, ‘center_h’, ‘center_v’, ‘axis_x’, ‘axis_y’.
reference (tuple, optional) – Reference panel position. If None, uses first panel.
- Return type:
Examples
>>> import figrecipe as fr >>> fig, axes = fr.subplots(2, 2) >>> # Align left column panels to left edge >>> fr.align_panels(fig, [(0, 0), (1, 0)], mode="left")
- scitex.plt.distribute_panels(fig, panels, direction='horizontal', spacing_mm=None)[source]
Distribute panels evenly with optional fixed spacing.
- Parameters:
- Return type:
Examples
>>> import figrecipe as fr >>> fig, axes = fr.subplots(1, 3) >>> # Distribute evenly >>> fr.distribute_panels(fig, [(0, 0), (0, 1), (0, 2)]) >>> # With fixed 5mm spacing >>> fr.distribute_panels(fig, [(0, 0), (0, 1), (0, 2)], spacing_mm=5)
- scitex.plt.extract_data(path)[source]
Extract data arrays from a saved recipe.
- Returns:
Nested dictionary: {call_id: {‘x’: array, ‘y’: array, …}}
- Return type:
- scitex.plt.get_graph_preset(name)
Get a preset by name.
- Parameters:
name (str) – Preset name. Built-in presets: ‘default’, ‘minimal’, ‘citation’, ‘dependency’, ‘social’, ‘biological’, ‘knowledge’.
- Returns:
Preset configuration dictionary.
- Return type:
- Raises:
ValueError – If preset name is not found.
- scitex.plt.list_graph_presets()
List all available presets with descriptions.
- Returns:
Dictionary mapping preset names to brief descriptions.
- Return type:
- scitex.plt.register_graph_preset(name, config, override=False)
Register a custom graph preset.
- Parameters:
- Raises:
ValueError – If preset already exists and override is False.
- Return type:
Examples
>>> from figrecipe._graph_presets import register_preset >>> register_preset('my_style', { ... 'layout': 'circular', ... 'node_color': '#e74c3c', ... 'node_size': 'degree', ... 'labels': True, ... })
- scitex.plt.load(path, calls=None, skip_decorations=False, apply_style=True)
Reproduce a figure from a recipe file or bundle.
- Parameters:
path (str or Path) – Path to recipe. Supports multiple formats: - .yaml/.yml file: Direct recipe file - .png/.jpg/etc: Image with associated .yaml - Directory: Bundle containing recipe.yaml - .zip: ZIP bundle (both old recipe.yaml format and new spec.json format)
calls (list of str, optional) – If provided, only reproduce these specific call IDs.
skip_decorations (bool) – If True, skip decoration calls.
apply_style (bool) – If True (default), apply saved style.
- Return type:
- Returns:
fig (matplotlib.figure.Figure) – Reproduced figure.
axes (Axes or list of Axes) – Reproduced axes.
- scitex.plt.save_bundle(fig, path, dpi=None, image_formats=None, save_hitmap=False, verbose=True)[source]
Save figure as a layered bundle (ZIP format).
Bundle structure inside ZIP:
spec.json # WHAT (semantic specification) style.json # HOW (appearance settings) data.csv # DATA (immutable source data) recipe.yaml # Reproducible recipe (for fr.reproduce()) exports/ figure.png figure_hitmap.png # only if save_hitmap=True
- Parameters:
fig (RecordingFigure) – The figure to save.
path (str or Path) – Output path (.zip will be added if not present).
dpi (int, optional) – DPI for exports (default from style or 300).
image_formats (list, optional) – Image formats to export (default: [‘png’]).
save_hitmap (bool) – Whether to save the per-pixel hitmap PNG used by the GUI editor for diff visualisation (default: False). Hitmap rendering is expensive and the typical save() caller doesn’t need it; opt in with save_hitmap=True when persisting bundles for the editor.
verbose (bool) – Whether to print status (default: True).
- Returns:
Path to saved ZIP bundle.
- Return type:
Path
- scitex.plt.reproduce(path, calls=None, skip_decorations=False, apply_style=True)[source]
Reproduce a figure from a recipe file or bundle.
- Parameters:
path (str or Path) – Path to recipe. Supports multiple formats: - .yaml/.yml file: Direct recipe file - .png/.jpg/etc: Image with associated .yaml - Directory: Bundle containing recipe.yaml - .zip: ZIP bundle (both old recipe.yaml format and new spec.json format)
calls (list of str, optional) – If provided, only reproduce these specific call IDs.
skip_decorations (bool) – If True, skip decoration calls.
apply_style (bool) – If True (default), apply saved style.
- Return type:
- Returns:
fig (matplotlib.figure.Figure) – Reproduced figure.
axes (Axes or list of Axes) – Reproduced axes.