smpl.plot

Simplified plotting.

acorr(x, *[, data])

Plot the autocorrelation of x.

angle_spectrum(x[, Fs, Fc, window, pad_to, ...])

Plot the angle spectrum.

annotate(text, xy[, xytext, xycoords, ...])

Annotate the point xy with text text.

arrow(x, y, dx, dy, **kwargs)

Add an arrow to the Axes.

auto(*adata[, funcs])

Automatically loop over functions and fit the best one.

autoscale([enable, axis, tight])

Autoscale the axis view to the data (toggle).

autumn()

Set the colormap to 'autumn'.

axes([arg])

Add an Axes to the current figure and make it the current Axes.

axhline([y, xmin, xmax])

Add a horizontal line across the Axes.

axhspan(ymin, ymax[, xmin, xmax])

Add a horizontal span (rectangle) across the Axes.

axis(*args[, emit])

Convenience method to get or set some axis properties.

axline(xy1[, xy2, slope])

Add an infinitely long straight line.

axvline([x, ymin, ymax])

Add a vertical line across the Axes.

axvspan(xmin, xmax[, ymin, ymax])

Add a vertical span (rectangle) across the Axes.

bar(x, height[, width, bottom, align, data])

Make a bar plot.

bar_label(container[, labels, fmt, ...])

Label a bar plot.

barbs(*args[, data])

Plot a 2D field of barbs.

barh(y, width[, height, left, align, data])

Make a horizontal bar plot.

bone()

Set the colormap to 'bone'.

box([on])

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

boxplot(x[, notch, sym, vert, whis, ...])

Draw a box and whisker plot.

broken_barh(xranges, yrange, *[, data])

Plot a horizontal sequence of rectangles.

cla()

Clear the current axes.

clabel(CS[, levels])

Label a contour plot.

clf()

Clear the current figure.

clim([vmin, vmax])

Set the color limits of the current image.

close([fig])

Close a figure window.

cohere(x, y[, NFFT, Fs, Fc, detrend, ...])

Plot the coherence between x and y.

colorbar([mappable, cax, ax])

Add a colorbar to a plot.

connect(s, func)

Bind function func to event s.

contour(*args[, data])

Plot contour lines.

contourf(*args[, data])

Plot filled contours.

cool()

Set the colormap to 'cool'.

copper()

Set the colormap to 'copper'.

csd(x, y[, NFFT, Fs, Fc, detrend, window, ...])

Plot the cross-spectral density.

cycler(*args, **kwargs)

Create a new Cycler object from a single positional argument, a pair of positional arguments, or the combination of keyword arguments.

data(*data[, function])

Plot datay against datax via fit()

delaxes([ax])

Remove an ~.axes.Axes (defaulting to the current axes) from its figure.

disconnect(cid)

Disconnect the callback with id cid.

draw()

Redraw the current figure.

draw_all([force])

Redraw all stale managed figures, or, if force is True, all managed figures.

draw_if_interactive()

Redraw the current figure if in interactive mode.

errorbar(x, y[, yerr, xerr, fmt, ecolor, ...])

Plot y versus x as lines and/or markers with attached errorbars.

eventplot(positions[, orientation, ...])

Plot identical parallel lines at the given positions.

figaspect(arg)

Calculate the width and height for a figure with a specified aspect ratio.

figimage(X[, xo, yo, alpha, norm, cmap, ...])

Add a non-resampled image to the figure.

figlegend(*args, **kwargs)

Place a legend on the figure.

fignum_exists(num)

Return whether the figure with the given id exists.

figtext(x, y, s[, fontdict])

Add text to figure.

figure([num, figsize, dpi, facecolor, ...])

Create a new figure, or activate an existing figure.

fill(*args[, data])

Plot filled polygons.

fill_between(x, y1[, y2, where, ...])

Fill the area between two horizontal curves.

fill_betweenx(y, x1[, x2, where, step, ...])

Fill the area between two vertical curves.

findobj([o, match, include_self])

Find artist objects.

fit(func, *adata, **kwargs)

Fit and plot function to datax and datay.

flag()

Set the colormap to 'flag'.

function(func, *args, **kwargs)

Plot function func between xmin and xmax

gca()

Get the current Axes.

gcf()

Get the current figure.

gci()

Get the current colorable artist.

get(obj, *args, **kwargs)

Return the value of an .Artist's property, or print all of them.

get_backend()

Return the name of the current backend.

get_cmap([name, lut])

Get a colormap instance, defaulting to rc values if name is None.

get_current_fig_manager()

Return the figure manager of the current figure.

get_figlabels()

Return a list of existing figure labels.

get_fignums()

Return a list of existing figure numbers.

get_plot_commands()

Get a sorted list of all of the plotting commands.

get_scale_names()

Return the names of the available scales.

getp(obj, *args, **kwargs)

Return the value of an .Artist's property, or print all of them.

ginput([n, timeout, show_clicks, mouse_add, ...])

Blocking call to interact with a figure.

gray()

Set the colormap to 'gray'.

grid([visible, which, axis])

Configure the grid lines.

hexbin(x, y[, C, gridsize, bins, xscale, ...])

Make a 2D hexagonal binning plot of points x, y.

hist(x[, bins, range, density, weights, ...])

Compute and plot a histogram.

hist2d(x, y[, bins, range, density, ...])

Make a 2D histogram plot.

hlines(y, xmin, xmax[, colors, linestyles, ...])

Plot horizontal lines at each y from xmin to xmax.

hot()

Set the colormap to 'hot'.

hsv()

Set the colormap to 'hsv'.

imread(fname[, format])

Read an image from a file into an array.

imsave(fname, arr, **kwargs)

Colormap and save an array as an image file.

imshow(X[, cmap, norm, aspect, ...])

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

inferno()

Set the colormap to 'inferno'.

install_repl_displayhook()

Connect to the display hook of the current shell.

interactive(b)

Set whether to redraw after every plotting command (e.g.

ioff()

Disable interactive mode.

ion()

Enable interactive mode.

isinteractive()

Return whether plots are updated after every plotting command.

jet()

Set the colormap to 'jet'.

legend(*args, **kwargs)

Place a legend on the Axes.

locator_params([axis, tight])

Control behavior of major tick locators.

loglog(*args, **kwargs)

Make a plot with log scaling on both the x and y axis.

magma()

Set the colormap to 'magma'.

magnitude_spectrum(x[, Fs, Fc, window, ...])

Plot the magnitude spectrum.

margins(*margins[, x, y, tight])

Set or retrieve autoscaling margins.

matshow(A[, fignum])

Display an array as a matrix in a new figure window.

minorticks_off()

Remove minor ticks from the Axes.

minorticks_on()

Display minor ticks on the Axes.

new_figure_manager(num, *args, **kwargs)

Create a new figure manager instance.

nipy_spectral()

Set the colormap to 'nipy_spectral'.

pause(interval)

Run the GUI event loop for interval seconds.

pcolor(*args[, shading, alpha, norm, cmap, ...])

Create a pseudocolor plot with a non-regular rectangular grid.

pcolormesh(*args[, alpha, norm, cmap, vmin, ...])

Create a pseudocolor plot with a non-regular rectangular grid.

phase_spectrum(x[, Fs, Fc, window, pad_to, ...])

Plot the phase spectrum.

pie(x[, explode, labels, colors, autopct, ...])

Plot a pie chart.

pink()

Set the colormap to 'pink'.

plasma()

Set the colormap to 'plasma'.

plot(*args[, scalex, scaley, data])

Plot y versus x as lines and/or markers.

plot2d(datax, datay, dataz, **kwargs)

Creates a 2D-Plot.

plot2d_kwargs(kwargs)

Set default plot2d_kwargs if not set.

plot_date(x, y[, fmt, tz, xdate, ydate, data])

[Discouraged] Plot coercing the axis to treat floats as dates.

plot_kwargs(kwargs)

Set default plot_kwargs if not set.

polar(*args, **kwargs)

Make a polar plot.

prism()

Set the colormap to 'prism'.

psd(x[, NFFT, Fs, Fc, detrend, window, ...])

Plot the power spectral density.

quiver(*args[, data])

Plot a 2D field of arrows.

quiverkey(Q, X, Y, U, label, **kwargs)

Add a key to a quiver plot.

rc(group, **kwargs)

Set the current .rcParams. group is the grouping for the rc, e.g., for lines.linewidth the group is lines, for axes.facecolor, the group is axes, 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_context([rc, fname])

Return a context manager for temporarily changing rcParams.

rcdefaults()

Restore the .rcParams from Matplotlib's internal default style.

register_cmap([name, cmap, override_builtin])

[Deprecated] Add a colormap to the set recognized by get_cmap().

rgrids([radii, labels, angle, fmt])

Get or set the radial gridlines on the current polar plot.

savefig(*args, **kwargs)

Save the current figure.

sca(ax)

Set the current Axes to ax and the current Figure to the parent of ax.

scatter(x, y[, s, c, marker, cmap, norm, ...])

A scatter plot of y vs.

sci(im)

Set the current image.

semilogx(*args, **kwargs)

Make a plot with log scaling on the x axis.

semilogy(*args, **kwargs)

Make a plot with log scaling on the y axis.

set_cmap(cmap)

Set the default colormap, and applies it to the current image if any.

set_loglevel(*args, **kwargs)

Set Matplotlib's root logger and root logger handler level, creating the handler if it does not exist yet.

setp(obj, *args, **kwargs)

Set one or more properties on an .Artist, or list allowed values.

show(*[, block])

Display all open figures.

specgram(x[, NFFT, Fs, Fc, detrend, window, ...])

Plot a spectrogram.

spring()

Set the colormap to 'spring'.

spy(Z[, precision, marker, markersize, ...])

Plot the sparsity pattern of a 2D array.

stackplot(x, *args[, labels, colors, ...])

Draw a stacked area plot.

stairs(values[, edges, orientation, ...])

A stepwise constant function as a line with bounding edges or a filled plot.

stem(*args[, linefmt, markerfmt, basefmt, ...])

Create a stem plot.

step(x, y, *args[, where, data])

Make a step plot.

streamplot(x, y, u, v[, density, linewidth, ...])

Draw streamlines of a vector flow.

subplot(*args, **kwargs)

Add an Axes to the current figure or retrieve an existing Axes.

subplot2grid(shape, loc[, rowspan, colspan, fig])

Create a subplot at a specific location inside a regular grid.

subplot_mosaic(mosaic, *[, sharex, sharey, ...])

Build a layout of Axes based on ASCII art or nested lists.

subplot_tool([targetfig])

Launch a subplot tool window for a figure.

subplots([nrows, ncols, sharex, sharey, ...])

Create a figure and a set of subplots.

subplots_adjust([left, bottom, right, top, ...])

Adjust the subplot layout parameters.

summer()

Set the colormap to 'summer'.

suptitle(t, **kwargs)

Add a centered suptitle to the figure.

switch_backend(newbackend)

Close all open figures and set the Matplotlib backend.

table([cellText, cellColours, cellLoc, ...])

Add a table to an ~.axes.Axes.

text(x, y, s[, fontdict])

Add text to the Axes.

thetagrids([angles, labels, fmt])

Get or set the theta gridlines on the current polar plot.

tick_params([axis])

Change the appearance of ticks, tick labels, and gridlines.

ticklabel_format(*[, axis, style, ...])

Configure the .ScalarFormatter used by default for linear Axes.

tight_layout(*[, pad, h_pad, w_pad, rect])

Adjust the padding between and around subplots.

title(label[, fontdict, loc, pad, y])

Set a title for the Axes.

tricontour(*args, **kwargs)

Draw contour lines on an unstructured triangular grid.

tricontourf(*args, **kwargs)

Draw contour regions on an unstructured triangular grid.

tripcolor(*args[, alpha, norm, cmap, vmin, ...])

Create a pseudocolor plot of an unstructured triangular grid.

triplot(*args, **kwargs)

Draw an unstructured triangular grid as lines and/or markers.

twinx([ax])

Make and return a second axes that shares the x-axis.

twiny([ax])

Make and return a second axes that shares the y-axis.

uninstall_repl_displayhook()

Disconnect from the display hook of the current shell.

unv(arr)

Return the nominal values of the numbers in NumPy array arr.

usd(arr)

Return the standard deviations of the numbers in NumPy array arr.

violinplot(dataset[, positions, vert, ...])

Make a violin plot.

viridis()

Set the colormap to 'viridis'.

vlines(x, ymin, ymax[, colors, linestyles, ...])

Plot vertical lines at each x from ymin to ymax.

waitforbuttonpress([timeout])

Blocking call to interact with the figure.

winter()

Set the colormap to 'winter'.

xcorr(x, y[, normed, detrend, usevlines, ...])

Plot the cross correlation between x and y.

xkcd([scale, length, randomness])

Turn on xkcd sketch-style drawing mode.

xlabel(xlabel[, fontdict, labelpad, loc])

Set the label for the x-axis.

xlim(*args, **kwargs)

Get or set the x limits of the current axes.

xscale(value, **kwargs)

Set the xaxis' scale.

xticks([ticks, labels, minor])

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

ylabel(ylabel[, fontdict, labelpad, loc])

Set the label for the y-axis.

ylim(*args, **kwargs)

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

yscale(value, **kwargs)

Set the yaxis' scale.

yticks([ticks, labels, minor])

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

Functions

smpl.plot.auto(*adata, funcs=None, **kwargs)[source]

Automatically loop over functions and fit the best one.

Parameters

funcsfunction array

functions to consider as fit. Default all smpl.functions.

**kwargsoptional

see plot_kwargs().

Returns

The best fit function and it’s parameters. Also a lambda function where the parameters are already applied.

smpl.plot.data(*data, function=None, **kwargs)[source]

Plot datay against datax via fit()

Parameters

dataxarray_like

X data either as unp.uarray or np.array or list

datayarray_like

Y data either as unp.uarray or np.array or list

functionfunc,optional

Fit function with parameters: x, params

**kwargsoptional

see plot_kwargs().

Returns

array_like

Optimized fit parameters of function to datax and datay

smpl.plot.fit(func, *adata, **kwargs)[source]

Fit and plot function to datax and datay.

Parameters

dataxarray_like

X data either as unp.uarray or np.array or list

datayarray_like

Y data either as unp.uarray or np.array or list

functionfunc

Fit function with parameters: x, params

**kwargsoptional

see plot_kwargs().

Fit parameters can be fixed via kwargs eg. a=5.

Returns

array_like

Optimized fit parameters of function to datax and datay. If datay is complex, both the real and imaginary part are returned.

Examples

>>> from smpl import functions as f
>>> from smpl import plot
>>> param = plot.fit([0,1,2],[0,1,2],f.line)
>>> plot.unv(param).round()[0]
1.0

(Source code, png, hires.png, pdf)

../_images/smpl-plot-1.png
smpl.plot.function(func, *args, **kwargs)[source]

Plot function func between xmin and xmax

Parameters

funcfunction

Function to be plotted between xmin and xmax, only taking array_like x as parameter

*argsoptional

arguments for func

**kwargsoptional

see plot_kwargs().

smpl.plot.plot2d(datax, datay, dataz, **kwargs)

Creates a 2D-Plot.

Parameters

**kwargsoptional

see plot2d_kwargs().

smpl.plot.plot2d_kwargs(kwargs)[source]

Set default plot2d_kwargs if not set. ================== ================== ================== plot2d_kwargs default description ================== ================== ================== xaxis None . yaxis None . zaxis None . logz True Colorbar in logarithmic scale. style pcolormesh Plot via an image (‘image’) or scatter (‘scatter’) or mesh (‘pcolormesh’). interpolation nearest Only ‘nearest’ or ‘bilinear’ for nonuniformimage. Check https://matplotlib.org/stable/gallery/images_contours_and_fields/interpolation_methods.html#interpolations-for-imshow cmap viridis Good default color map for missing datapoints since it does not include white. ================== ================== ==================

smpl.plot.plot_kwargs(kwargs)[source]

Set default plot_kwargs if not set. ================== ================== ================== plot_kwargs default description ================== ================== ================== title None Plot title xlabel X axis label ylabel Y axis label label None Legend name of plotted data fmt . Format for plotting fit function units None Units of the fit parameters as strings. Displayed in the Legend save None File to save the plot lpos 0 Legend position tight True tight_layout prange None Limit the plot of the fit to given range sigmas 0 Color the array of given sigma times uncertainty. Only works if the fit function is coded with unp data_sigmas 1 Color the array of given sigma times uncertainty. Only works if the data has uncertainties init False Initialize a new plot ss True save, add legends and grid to the plot also_data True also plot the data also_fit True also plot the fit auto_fit False automatically fit logy False logarithmic x axis logx False logarithmic y axis function_color None Color of the function plot data_color None Color of the data plot fit_color None Color of the fit plot fit_fmt - Format of the fit plot residue False Display difference between fit and data in a second plot residue_err True Differences between fit and data will have errorbars show False Call plt.show() size None Size of the plot as a tuple (x,y). Only has an effect if init is True number_format {0:.4g} Format to display numbers. interpolate False Enable interpolation of the data. interpolate_fmt - Either format string or linestyle tuple. interpolate_label None Label for the interpolation. extrapolate True Enable extrapolation of whole data if fit range is limited by frange or fselector. extrapolate_min None Lower extrapolation bound extrapolate_max None Higher extrapolation bound extrapolate_fmt – Format of the extrapolation line extrapolate_hatch || Extrapolation shape/hatch for filled area in case of sigmas>0. See https://matplotlib.org/stable/gallery/shapes_and_collections/hatch_style_reference.html bbox_to_anchor None Position in a tuple (x,y),Shift position of the legend out of the main pane. ncol None Columns in the legend if used with bbox_to_anchor. steps 1000 resolution of the plotted function fitinline False No newlines for each fit parameter grid True Enable grid for the plot hist False Enable histogram plot stairs False Enable stair plot capsize 5 size of cap on error bar plot axes None set current axis linestyle None linestyle, only active if fmt`=None xspace linspace xspace gets called with xspace(xmin,xmax,steps) in :func:`function to get the points of the function that will be drawn. alpha 0.2 alpha value for the fill_between plot ================== ================== ==================

Set default fit_kwargs if not set. ================== ================== ================== fit_kwargs default description ================== ================== ================== params None Initial fit parameters fixed_params True Enable fixing parameters by choosing the same-named variables from kwargs. maxfev 10000 Maximum function evaluations during fitting. epsfcn 0.0001 Suitable step length for jacobian approximation. xvar None Variable in fit function parameters that corresponds to the x axis. If it is None the last of the alphabetical sorted parameters is used. autotqdm True Auto fitting display tqdm fitter Fitter.AUTO Choose from :class:`Fitter`s. ================== ================== ==================

Set default data_kwargs if not set. ================== ================== ================== data_kwargs default description ================== ================== ================== frange None Limit the fit to given range. First integer is the lowest and second the highest index. fselector None Function that takes x and y as parameters and returns an array mask in order to limit the data points for fitting. Alternatively a mask for selecting elements from datax and datay. sortbyx True Enable sorting the x and y data so that x is sorted. bins 0 Number of bins for histogram binunc poisson_dist Number of bins for histogram xerror True enable xerrors yerror True enable yerrors ================== ================== ==================

smpl.plot.unv(arr)[source]

Return the nominal values of the numbers in NumPy array arr.

Elements that are not numbers with uncertainties (derived from a class from this module) are passed through untouched (because a numpy.array can contain numbers with uncertainties and pure floats simultaneously).

If arr is of type unumpy.matrix, the returned array is a numpy.matrix, because the resulting matrix does not contain numbers with uncertainties.

smpl.plot.usd(arr)[source]

Return the standard deviations of the numbers in NumPy array arr.

Elements that are not numbers with uncertainties (derived from a class from this module) are passed through untouched (because a numpy.array can contain numbers with uncertainties and pure floats simultaneously).

If arr is of type unumpy.matrix, the returned array is a numpy.matrix, because the resulting matrix does not contain numbers with uncertainties.