komplot

Convenient plotting functions with interactive features.

Alternative high-level interface to selected matplotlib plotting functions.

Functions

close([fig])

Close figure(s).

config_notebook_plotting([backend])

Configure plotting functions for inline plotting.

contour(z[, x, y, xlog, ylog, levels, ...])

Contour plot of a 2D surface.

contour_(*args, **kwargs)

Contour plot of a 2D surface.

figure_event_manager(fig[, error])

Get the figure event manager attached to a figure.

imview(image, *[, interpolation, origin, ...])

Display an image.

imview_(*args, **kwargs)

Display an image.

plot(*args[, xlog, ylog, xlabel, ylabel, ...])

Plot points or lines in 2D.

plot_(*args, **kwargs)

Plot points or lines in 2D.

set_ipython_plot_backend([backend])

Set matplotlib backend within an ipython shell.

set_notebook_plot_backend([backend])

Set matplotlib backend within a Jupyter Notebook shell.

surface(z[, x, y, elev, azim, roll, alpha, ...])

Plot a 2D surface in 3D.

surface_(*args, **kwargs)

Plot a 2D surface in 3D.

volview(volume, *[, slice_axis, ...])

Display a slice of a volume.

volview_(*args, **kwargs)

Display a slice of a volume.

Classes

AxesEventManager(axes, fig_event_man, plot)

Base class for axes-based event managers.

ColorbarEventManager(axes, fig_event_man, cbplot)

Manager for colorbar events.

ColorbarPlot(*, figure, axes, axesimage, ...)

State of plot supporting axis zoom and a colorbar.

ContourPlot(*, figure, axes, axesimage, ...)

State of contour plot.

FigureEventManager(fig[, fig_scale])

Manager for figure-based events.

GenericPlot(*, figure, axes)

Generic plot state.

ImageView(*, figure, axes, axesimage, ...)

State of imview plot.

ImageViewEventManager(axes, fig_event_man, iview)

Manager for axes-based events.

LinePlot(*, figure, axes, line2d)

State of 2d line/point plot.

SurfacePlot(*, figure, axes, poly3dc, qcntset)

State of surface plot.

VolumeView(*, figure, axes, axesimage, ...)

State of volview plot.

VolumeViewEventManager(axes, fig_event_man, ...)

Manager for axes-based events.

ZoomEventManager(axes, fig_event_man, zplot)

Manager for axis zoom events.

ZoomablePlot(*, figure, axes)

State for a plot supporting axis zoom.

komplot.contour(z, x=None, y=None, *, xlog=False, ylog=False, levels=5, clabel_inline=True, clabel_format=None, clabel_fontsize=10, cmap=None, vmin=None, vmax=None, alpha=1.0, xlabel=None, ylabel=None, xylabel_fontsize=None, title=None, figsize=None, fignum=None, ax=None)

Contour plot of a 2D surface.

Contour plot of a 2D surface together with pseudo-color image representation of the surface. Supports the following features:

Parameters:
  • z (ndarray) – Contour data 2d array to plot.

  • x (Optional[ndarray]) – Values for x-axis of the plot.

  • y (Optional[ndarray]) – Values for y-axis of the plot.

  • xlog (bool) – Set x-axis to log scale.

  • ylog (bool) – Set y-axis to log scale.

  • levels (Union[int, Sequence[float]]) – An int specifying the number of contours to plot, or a sequence specifying the specific contour levels to plot.

  • clabel_inline (bool) – Value of parameter inline of clabel().

  • clabel_format (Optional[str]) – Format string for contour labels.

  • clabel_fontsize (Optional[int]) – Contour label font size. No contour labels are displayed if set to 0 or None.

  • cmap (Union[Colormap, str, None]) – Color map for color mesh drawn under contours. If none specifed, defaults to matplotlib.cm.YlOrRd.

  • vmin (Optional[float]) – Set lower bound for the color map (see the corresponding parameter of imshow()).

  • vmax (Optional[float]) – Set upper bound for the color map (see the corresponding parameter of imshow()).

  • alpha (float) – Underlying image display alpha value.

  • xlabel (Optional[str]) – Label for x-axis.

  • ylabel (Optional[str]) – Label for y-axis.

  • xylabel_fontsize (Optional[int]) – Axis label font size. The default font size is used if set to None.

  • title (Optional[str]) – Figure title.

  • figsize (Optional[Tuple[int, int]]) – Specify dimensions of figure to be creaed as a tuple (width, height) in inches.

  • fignum (Optional[int]) – Figure number of figure to be created.

  • ax (Optional[Axes]) – Plot in specified axes instead of creating one.

Return type:

ContourPlot

Returns:

Contour plot state object.

class komplot.ContourPlot(*, figure, axes, axesimage, divider, cbar_axes, qcntset)

Bases: ColorbarPlot

State of contour plot.

Parameters:
komplot.imview(image, *, interpolation='nearest', origin='upper', vmin_quantile=0.0, norm=None, show_cbar=False, cmap=None, title=None, figsize=None, fignum=None, ax=None)

Display an image.

Display an image. Pixel values are displayed when the pointer is over valid image data. Supports the following features:

Parameters:
  • image (ndarray) – Image to display. It should be two or three dimensional, with the third dimension, if present, representing color and opacity channels, and having size 3 or 4.

  • interpolation (str) – Specify type of interpolation used to display image (see interpolation parameter of imshow()).

  • origin (str) – Specify the origin of the image support. Valid values are “upper” and “lower” (see origin parameter of imshow()). The location of the plot x-ticks indicates which of these options was selected.

  • vmin_quantile (float) – Specify color map vmin and vmax based on pixel value quantiles. The default of 0.0 corresponds to setting vmin and vmax to the minimum and maximum pixel value respectively. If it is non-zero, vmin and vmax are set to the vmin_quantile quantile and the 1 - vmin_quantile respectively.

  • norm (Optional[Normalize]) – Specify the Normalize instance used to scale pixel values for input to the color map. If not None, it is used to define the color map range instead of the vmin and vmax determined by vmin_quantile.

  • show_cbar (Optional[bool]) – Flag indicating whether to display a colorbar. If set to None, create an invisible colorbar so that the image occupies the same amount of space in a subplot as one with a visible colorbar.

  • cmap (Union[Colormap, str, None]) – Color map for image or volume slices. If none specifed, defaults to matplotlib.cm.Greys_r for monochrome image.

  • title (Optional[str]) – Figure title.

  • figsize (Optional[Tuple[int, int]]) – Specify dimensions of figure to be creaed as a tuple (width, height) in inches.

  • fignum (Optional[int]) – Figure number of figure to be created.

  • ax (Optional[Axes]) – Plot in specified axes instead of creating one.

Return type:

ImageView

Returns:

Image view state object.

Raises:

ValueError – If the input array is not of the required shape.

class komplot.ImageView(*, figure, axes, axesimage, divider, cbar_axes)

Bases: ColorbarPlot

State of imview plot.

Parameters:
class komplot.ImageViewEventManager(axes, fig_event_man, iview, zoom_scale=2.0, cmap_delta=0.02)

Bases: ColorbarEventManager

Manager for axes-based events.

Manage mouse scroll and slider widget events. The following interactive features are supported:

Mouse wheel scroll

Zoom in or out at current cursor location.

Mouse wheel scroll in bottom half of colorbar

Increase or decrease colormap vmin.

Mouse wheel scroll in top half of colorbar

Increase or decrease colormap vmax.

Parameters:
  • axes (Axes) – Axes to which this manager is attached.

  • fig_event_man (FigureEventManager) – The figure event manage for the figure to which axes belong.

  • iview (ImageView) – A plot state of type ImageView.

  • zoom_scale (float) – Scaling factor for mouse wheel zoom.

  • cmap_delta (float) – Fraction of colormap range for vmin/vmax shifts.

komplot.volview(volume, *, slice_axis=0, interpolation='nearest', origin='upper', vmin_quantile=0.0, norm=None, show_cbar=False, cmap=None, title=None, figsize=None, fignum=None, ax=None)

Display a slice of a volume.

Display a slice of a volume. Pixel values are displayed when the pointer is over valid image data. Supports the following features:

Parameters:
  • volume (ndarray) – Volume to display. It should be three or four dimensional. If four dimensional, the final dimension after exclusion of the axis identified by slice_axis represents color and opacity channels, should have size 3 or 4.

  • slice_axis (int) – The axis of volume, if any, from which to select volume slices for display.

  • interpolation (str) – Specify type of interpolation used to display image (see interpolation parameter of imshow()).

  • origin (str) – Specify the origin of the image support. Valid values are “upper” and “lower” (see origin parameter of imshow()). The location of the plot x-ticks indicates which of these options was selected.

  • vmin_quantile (float) – Specify color map vmin and vmax based on pixel value quantiles. The default of 0.0 corresponds to setting vmin and vmax to the minimum and maximum pixel value respectively. If it is non-zero, vmin and vmax are set to the vmin_quantile quantile and the 1 - vmin_quantile respectively.

  • norm (Optional[Normalize]) – Specify the Normalize instance used to scale pixel values for input to the color map. If not None, it is used to define the color map range instead of the vmin and vmax determined by vmin_quantile.

  • show_cbar (Optional[bool]) – Flag indicating whether to display a colorbar. If set to None, create an invisible colorbar so that the image occupies the same amount of space in a subplot as one with a visible colorbar.

  • cmap (Union[Colormap, str, None]) – Color map for image or volume slices. If none specifed, defaults to matplotlib.cm.Greys_r for monochrome image.

  • title (Optional[str]) – Figure title.

  • figsize (Optional[Tuple[int, int]]) – Specify dimensions of figure to be creaed as a tuple (width, height) in inches.

  • fignum (Optional[int]) – Figure number of figure to be created.

  • ax (Optional[Axes]) – Plot in specified axes instead of creating one.

Return type:

VolumeView

Returns:

Volume view state object.

Raises:

ValueError – If the input array is not of the required shape.

class komplot.VolumeView(*, figure, axes, axesimage, divider, cbar_axes, volume=None, slice_index=0, slider_axes=None, slider=None)

Bases: ImageView

State of volview plot.

Parameters:
  • figure (Figure) – Plot figure.

  • axes (Axes) – Plot axes.

  • axesimage (AxesImage) – The AxesImage associated with the colorbar.

  • divider (AxesDivider) – The AxesDivider used to create axes for the colorbar.

  • cbar_axes (Optional[Axes]) – The axes of the colorbar.

  • volume (Optional[ndarray]) – The volume array.

  • slice_index (int) – The index of the volume slice.

  • slider_axes (Optional[Axes]) – The axes of the volume slice index selection slider.

  • slider (Optional[Slider]) – The volume slice index selection slider widget.

set_volume_slice(index, update_slider=True, suppress_events=False)[source]

Set the volume slice index.

Set the volume slice index.

Parameters:
  • index (int) – Index of volume slice to display.

  • update_slider (bool) – If True also update the volume slice selection sider widget to the selected index.

  • suppress_events (bool) – If True, suppress events generated by the slider update.

class komplot.VolumeViewEventManager(axes, fig_event_man, iview, zoom_scale=2.0, cmap_delta=0.02)

Bases: ImageViewEventManager

Manager for axes-based events.

Manage mouse scroll and slider widget events. The following interactive features are supported:

Mouse wheel scroll

Zoom in or out at current cursor location.

Mouse wheel scroll with shift key depressed

Shift the displayed slice when displaying a volume.

Click or drag slider widget

Change the displayed slice when displaying a volume.

Mouse wheel scroll in bottom half of colorbar

Increase or decrease colormap vmin.

Mouse wheel scroll in top half of colorbar

Increase or decrease colormap vmax.

Parameters:
  • axes (Axes) – Axes to which this manager is attached.

  • fig_event_man (FigureEventManager) – The figure event manage for the figure to which axes belong.

  • iview (VolumeView) – A plot state of type VolumeView.

  • zoom_scale (float) – Scaling factor for mouse wheel zoom.

  • cmap_delta (float) – Fraction of colormap range for vmin/vmax shifts.

scroll_event_handler(event)[source]

Calback for mouse scroll events.

Parameters:

event (Event)

shift_slice_event_handler(event)[source]

Handle shift slice event.

Parameters:

event (Event)

slider_event_handler(val)[source]

Calback for slider widget changes.

Parameters:

val (int)

komplot.plot(*args, xlog=False, ylog=False, xlabel=None, ylabel=None, title=None, legend=None, legend_loc=None, figsize=None, fignum=None, ax=None, **kwargs)

Plot points or lines in 2D.

Plot points or lines in 2D. Largely replicates the interface of plot(), with the following execeptions

Parameters:
  • *args – Plot specification in form [x], y, [fmt], etc. corresponding to the signature of plot().

  • xlog (bool) – Set x axis to log scale if True.

  • ylog (bool) – Set y axis to log scale if True.

  • xlabel (Optional[str]) – Label for x-axis.

  • ylabel (Optional[str]) – Label for y-axis.

  • title (Optional[str]) – Figure title.

  • legend (Optional[Sequence[str]]) – List of legend strings.

  • legend_loc (Optional[str]) – Legend location string as supported by loc parameter of legend().

  • figsize (Optional[Tuple[int, int]]) – Specify dimensions of figure to be creaed as a tuple (width, height) in inches.

  • fignum (Optional[int]) – Figure number of figure to be created.

  • ax (Optional[Axes]) – Plot in specified axes instead of creating one.

  • **kwargs – All keyword arguments of plot() are supported, such as those specifying Line2D properties (if not specified, the defaults for line width (lw) and marker size (ms) are 1.5 and 6.0 respectively), as well as the following additional keyword arguments. When parameters xlog or ylog are specified, additional properties of the log-scale axes may be specified via parameters base, subs, nonpositive, basex, subsx, nonposx, basey, subsy, and nonposy, supported by loglog().

Return type:

LinePlot

Returns:

Line/point plot state object.

class komplot.LinePlot(*, figure, axes, line2d)

Bases: ZoomablePlot

State of 2d line/point plot.

Parameters:
komplot.surface(z, x=None, y=None, *, elev=None, azim=None, roll=None, alpha=1.0, cmap=None, levels=None, xlabel=None, ylabel=None, zlabel=None, labelpad=8.0, title=None, figsize=None, fignum=None, ax=None)

Plot a 2D surface in 3D.

Plot a 2D surface in 3D, together with an optional contour plot in the x-y plane below the surface. Supports the following features:

Parameters:
  • z (ndarray) – Surface data 2d array to plot.

  • x (Optional[ndarray]) – Values for x-axis of the plot.

  • y (Optional[ndarray]) – Values for y-axis of the plot.

  • elev (Optional[float]) – Elevation angle (in degrees); see corresponding parameter of view_init().

  • azim (Optional[float]) – Azimuth angle (in degrees); see corresponding parameter of view_init().

  • roll (Optional[float]) – Roll angle (in degrees); see corresponding parameter of view_init().

  • alpha (float) – Transparency, if specified should be a float between 0.0 and 1.0.

  • cmap (Union[Colormap, str, None]) – Color map for surface. If none specifed, defaults to matplotlib.cm.YlOrRd.

  • levels (Union[int, Sequence[int], None]) – If not None, plot contours of the surface on the lower end of the z-axis. An int specifies the number of contours to plot, and a sequence specifies the specific contour levels to plot.

  • xlabel (Optional[str]) – Label for x-axis.

  • ylabel (Optional[str]) – Label for y-axis.

  • zlabel (Optional[str]) – Label for z-axis.

  • labelpad (float) – Label padding.

  • title (Optional[str]) – Figure title.

  • figsize (Optional[Tuple[int, int]]) – Specify dimensions of figure to be creaed as a tuple (width, height) in inches.

  • fignum (Optional[int]) – Figure number of figure to be created.

  • ax (Optional[Axes]) – Plot in specified axes instead of creating one.

Return type:

SurfacePlot

Returns:

Surface plot state object.

class komplot.SurfacePlot(*, figure, axes, poly3dc, qcntset)

Bases: GenericPlot

State of surface plot.

Parameters:
komplot.figure_event_manager(fig, error=True)

Get the figure event manager attached to a figure.

Parameters:
  • fig (Figure) – Figure.

  • error (bool) – If True, raise an exception if no figure manager attached.

Raises:

RuntimeError – If error parameter is True and no figure manager attached.

Return type:

FigureEventManager

class komplot.FigureEventManager(fig, fig_scale=1.1)

Bases: object

Manager for figure-based events.

Manage key-press events, and maintain a record of associated axes and their manager instances. The key-press events provide monitoring of keys used as modifiers for other events (e.g. mouse scroll while shift is depressed) and also support the following keyboard shortcuts:

q

Close figure. (This is also a standard keyboard shortcut.)

PageUp/PageDown

Increase or decrease figure size by a scaling factor.

Note that key-press detection is not functional in Jupyter notebooks, including with the interactive ipympl matplotlib backend.

Parameters:
  • fig (Figure) – Figure to which this manager is attached.

  • fig_scale (float) – Scaling factor for figure scaling keyboard shortcut.

static attached_manager(fig, error=False)[source]

Get the figure manager attached to a figure.

Parameters:
  • fig (Figure) – Figure.

  • error (bool) – If True, raise an exception if no figure manager attached.

Raises:

RuntimeError – If error parameter is True and no figure manager attached.

get_axevman_for_axes(ax)[source]

Retrieve the axes event manager associated with an axes.

Parameters:

ax (Axes) – Axes.

Returns:

The axes event manager associated with an axes.

register_axevman_for_axes(ax, axem)[source]

Register the axes event manager for an axes instance.

Parameters:
set_cmap_share(axes)[source]

Define a set of colormap sharing axes.

Parameters:

axes (Union[List[Axes], ndarray]) – List of axes.

set_slice_share(axes)[source]

Define a set of volume slice sharing axes.

Parameters:

axes (Union[List[Axes], ndarray]) – List of axes.

class komplot.AxesEventManager(axes, fig_event_man, plot)

Bases: object

Base class for axes-based event managers.

Base class for axes-based event managers.

Parameters:
  • axes (Axes) – Axes to which this manager is attached.

  • fig_event_man (FigureEventManager) – The figure event manage for the figure to which axes belong.

  • plot (GenericPlot) – A plot state object.

class komplot.ZoomEventManager(axes, fig_event_man, zplot, zoom_scale=2.0)

Bases: AxesEventManager

Manager for axis zoom events.

Manage axis zoom via mouse wheel scroll.

Parameters:
  • axes (Axes) – Axes to which this manager is attached.

  • fig_event_man (FigureEventManager) – The figure event manage for the figure to which axes belong.

  • zplot (ZoomablePlot) – A plot state of type ZoomablePlot.

  • zoom_scale (float) – Scaling factor for mouse wheel zoom.

scroll_event_handler(event)[source]

Calback for mouse scroll events.

Parameters:

event (Event)

xylim_changed_handler(axes)[source]

Callback for changes to axes limits.

Parameters:

axes (Axes)

zoom_event_handler(event)[source]

Handle axes zoom event.

Parameters:

event (Event)

class komplot.ColorbarEventManager(axes, fig_event_man, cbplot, zoom_scale=2.0, cmap_delta=0.02)

Bases: ZoomEventManager

Manager for colorbar events.

Manage colormap vmin and vmax adjustment via mouse scroll in a colorbar. Scrolling in the bottom/left half of the colorbar adjusts vmin, and scrolling in the top/right half of the colorbar adjusts vmax. Axis zoom events on mouse scroll are also supported via the ZoomEventManager base class.

Parameters:
  • axes (Axes) – Axes to which this manager is attached.

  • fig_event_man (FigureEventManager) – The figure event manage for the figure to which axes belong.

  • cbplot (ColorbarPlot) – A plot state of type ColorbarPlot.

  • zoom_scale (float) – Scaling factor for mouse wheel zoom.

  • cmap_delta (float) – Fraction of colormap range for vmin/vmax shifts.

cbar_event_rel_pos(event)[source]

Determine relative position of event in a colorbar.

Parameters:

event (Event)

cmap_vminmax_event_handler(event, rel_pos)[source]

Colorbar limits adjust callback.

Parameters:

rel_pos (float)

scroll_event_handler(event)[source]

Calback for mouse scroll events.

Parameters:

event (Event)

class komplot.GenericPlot(*, figure, axes)

Bases: object

Generic plot state.

Parameters:
  • figure (Figure) – Plot figure.

  • axes (Axes) – Plot axes.

toolbar_message(msg)[source]

Display message in toolbar if present.

Parameters:

msg (str) – Message string.

class komplot.ZoomablePlot(*, figure, axes)

Bases: GenericPlot

State for a plot supporting axis zoom.

Parameters:
  • figure (Figure) – Plot figure.

  • axes (Axes) – Plot axes.

zoom_toolbar_message()[source]

Display toolbar message.

This function is called on axis zoom events.

zoom_view(xdata, ydata, scale_factor)[source]

Zoom the view in this axes.

Parameters:
  • xdata (float) – Data x coordinate of event location.

  • ydata (float) – Data y coordinate of event location.

  • scale_factor (float) – Zoom scale factor (greater than unity for zoom out, less than unity for zoom in).

class komplot.ColorbarPlot(*, figure, axes, axesimage, divider, cbar_axes)

Bases: ZoomablePlot

State of plot supporting axis zoom and a colorbar.

Parameters:
shift_cmap_vmax(rel_delta)[source]

Change colormap vmax.

Parameters:

rel_delta (float) – Signed relative change in colormap vmax value.

shift_cmap_vmin(rel_delta)[source]

Change colormap vmin.

Parameters:

rel_delta (float) – Signed relative change in colormap vmin value.

komplot.close(fig=None)

Close figure(s).

Close figure(s). If a figure object reference or figure number is provided, close the specified figure, otherwise close all figures.

Parameters:

fig (Union[Figure, int, None]) – Figure object or number of figure to close. If None, close all figures.

komplot.config_notebook_plotting(backend=None)

Configure plotting functions for inline plotting.

Configure plotting functions for inline plotting within a Jupyter notebook shell. This function has no effect when not within a notebook shell, and may therefore be used within a normal Python script. If environment variable MATPLOTLIB_IPYNB_BACKEND is set, the matplotlib backend is explicitly set to the specified value.

Parameters:

backend (Optional[str]) – Name of backend to be passed to set_notebook_plot_backend().

komplot.set_ipython_plot_backend(backend='qt')

Set matplotlib backend within an ipython shell.

Set matplotlib backend within an ipython shell. This function has the same effect as the line magic %matplotlib [backend] but is called as a function and includes a check to determine whether the code is running in an ipython shell, so that it can safely be used within a normal python script since it has no effect when not running in an ipython shell.

Parameters:

backend (str) – Name of backend to be passed to the %matplotlib line magic command.

komplot.set_notebook_plot_backend(backend=None)

Set matplotlib backend within a Jupyter Notebook shell.

Set matplotlib backend within a Jupyter Notebook shell. This function has the same effect as the line magic %matplotlib [backend] but is called as a function and includes a check to determine whether the code is running in a notebook shell, so that it can safely be used within a normal python script since it has no effect when not running in a notebook shell.

Parameters:

backend (Optional[str]) – Name of backend to be passed to the %matplotlib line magic command. Defaults to “ipympl” if ipympl is installed, otherwise defaults to “inline”.

komplot.contour_(*args, **kwargs)

Contour plot of a 2D surface.

This version of contour() discards the return value, for use in Jupyter notebooks where the return value is not needed, and which would clutter the following output cell.

komplot.imview_(*args, **kwargs)

Display an image.

This version of imview() discards the return value, for use in Jupyter notebooks where the return value is not needed, and which would clutter the following output cell.

komplot.plot_(*args, **kwargs)

Plot points or lines in 2D.

This version of plot() discards the return value, for use in Jupyter notebooks where the return value is not needed, and which would clutter the following output cell.

komplot.surface_(*args, **kwargs)

Plot a 2D surface in 3D.

This version of surface() discards the return value, for use in Jupyter notebooks where the return value is not needed, and which would clutter the following output cell.

komplot.volview_(*args, **kwargs)

Display a slice of a volume.

This version of volview() discards the return value, for use in Jupyter notebooks where the return value is not needed, and which would clutter the following output cell.