KomPlot Usage Examples

This example demonstrates the use of the main komplot plotting functions.

[1]:
# Configure environment when running in google colab
try:
    from google.colab import output
    import os
    os.environ["MPLBACKEND"] = "notebook"  # workaround for install failure of unknown origin
    os.environ["MATPLOTLIB_IPYNB_BACKEND"] = "inline"  # ipympl broken on colab ( see googlecolab/colabtools#5425 )
    %pip install "komplot[examples] @ git+https://github.com/bwohlberg/komplot"
except ImportError:
    pass
[2]:
import numpy as np
from imageio.v3 import imread

import komplot as kplt
kplt.config_notebook_plotting()  # Configure Jupyter notebook plotting
kplt.rcParams['figure.max_open_warning'] = 0  # Suppress too many open figures warning

Two-Dimensional Plots

Define an x array and three 1-d functions of it.

[3]:
x = np.linspace(-1, 1, 101)
y1 = np.abs(x)
y2 = np.abs(x)**1.5
y3 = x**2

Plot the three functions on the same axes. Note the use of the function plot_, which is a variant of plot that discards its return value to avoid cluttering the following output cell. All of the main komplot plotting functions have corresponding return-value-discarding variants. The same effect can be achieved by using the primary plotting function call, followed by a semi-colon, as in some of the following examples.

[4]:
kplt.plot_(x, np.stack((y1, y2, y3)).T, xlabel='x', ylabel='y', title='Plot Example',
           legend=('$|x|$', '$|x|^{(3/2)}$', '$x^2$'), legend_loc='upper center')

We can also create a plot and then add to it. In this case we need to create the figure object separately and pass it as argument to the komplot.plot function so that it doesn’t automatically call fig.show after the first plot call.

[5]:
fig, ax = kplt.subplots()
kplt.plot(x, np.stack((y1, y2, y3)).T, xlabel='x', ylabel='y', title='Plot Example',
           legend=('$|x|$', '$|x|^{(3/2)}$', '$x^2$'), legend_loc='upper center', ax=ax);
kplt.plot(x[::5], y1[::5], lw=0, ms=8.0, marker='o', ax=ax);
fig.show()

Surface and Contour Plots

Define x and y arrays and a 2-d surface on x, y.

[6]:
x = np.linspace(0, 2, 50)[np.newaxis, :]
y = np.linspace(-1, 1, 51)[:, np.newaxis]
z = np.sin(y) * np.cos(2*x*y)

Plot a surface plot of the surface, including contour lines at the bottom of the z axis.

[7]:
kplt.surface(z, x, y, elev=25, azim=-25, xlabel='x', ylabel='y', zlabel='z',
             title='Surface Plot Example', levels=5, figsize=(7, 6));

Plot a contour plot of the same surface.

[8]:
kplt.contour(z, x, y, xlabel='x', ylabel='y', title='Contour Plot Example', figsize=(6, 5));

We can also plot within subplots of the same figure.

[9]:
fig, ax = kplt.subplots(nrows=1, ncols=2, figsize=(10.0, 4.5))
fig.suptitle('Figure Title', fontsize=14)
kplt.surface(z, x, y, xlabel='x', ylabel='y', zlabel='z', title='Surface Plot Example',
             ax=ax[0]);
kplt.contour(z, x, y, xlabel='x', ylabel='y', title='Contour Plot Example', ax=ax[1]);
fig.tight_layout()
fig.subplots_adjust(wspace=0.4)
fig.show()

Image Display

Load an example colour image and create a corresponding grayscale version.

[10]:
img = imread("imageio:camera.png")
imc = imread("imageio:immunohistochemistry.png")
Imageio: 'camera.png' was not found on your computer; downloading it now.
Try 1. Download from https://github.com/imageio/imageio-binaries/raw/master/images/camera.png (136 kB)
Downloading: 8192/139512 bytes (5.9%)139512/139512 bytes (100.0%)
  Done
File saved as /home/docs/.imageio/images/camera.png.
Imageio: 'immunohistochemistry.png' was not found on your computer; downloading it now.
Try 1. Download from https://github.com/imageio/imageio-binaries/raw/master/images/immunohistochemistry.png (459 kB)
Downloading: 8192/470201 bytes (1.7%)470201/470201 bytes (100.0%)
  Done
File saved as /home/docs/.imageio/images/immunohistochemistry.png.

Display the example colour image.

[11]:
kplt.imview_(imc, title='Image View Example', figsize=(6, 6))

Display the grayscale image with a false-colour colour map, with a colour bar display of the color map.

[12]:
kplt.imview(img, cmap=kplt.cm.coolwarm, title='Image View Example', show_cbar=True,
            figsize=(7, 6));

We can view both images as subplots within the same figure, but the colour bar on the second image changes its aspect ratio, which has the undesirable result of the two images being displayed with different sizes.

[13]:
fig, ax = kplt.subplots(nrows=1, ncols=2, figsize=(10, 5))
fig.suptitle('Figure Title', fontsize=14)
kplt.imview(imc, title='Colour Image', ax=ax[0]);
kplt.imview(img, cmap=kplt.cm.coolwarm, title='Monochrome Image', show_cbar=True, ax=ax[1]);
fig.show()

One solution is to adjust the ratios of the widths of the two subplots. We can also share x and y axes so that a zoom in one image is replicated in the other (this is, of course, only possible in the interactive version of this demonstration script).

[14]:
fig, ax = kplt.subplots(nrows=1, ncols=2, sharex=True, sharey=True,
                        gridspec_kw={'width_ratios': [1, 1.07]}, figsize=(10, 4))
fig.suptitle('Figure Title', fontsize=14)
kplt.imview(imc, title='Colour Image', ax=ax[0]);
kplt.imview(img, cmap=kplt.cm.coolwarm, title='Monochrome Image', show_cbar=True, ax=ax[1]);
fig.show()

An alternative solution is to add an invisible colorbar to the first image so that they have the same size. This can be achieved by setting show_cbar=None instead of show_cbar=True.

[15]:
fig, ax = kplt.subplots(nrows=1, ncols=2, sharex=True, sharey=True, figsize=(10, 4))
fig.suptitle('Figure Title', fontsize=14)
kplt.imview(imc, title='Colour Image', show_cbar=None, ax=ax[0]);
kplt.imview(img, cmap=kplt.cm.coolwarm, title='Monochrome Image', show_cbar=True, ax=ax[1]);
fig.show()

Volume Slice Display

Load example volume.

[16]:
vol = imread("imageio:stent.npz")
Imageio: 'stent.npz' was not found on your computer; downloading it now.
Try 1. Download from https://github.com/imageio/imageio-binaries/raw/master/images/stent.npz (805 kB)
Downloading: 8192/824612 bytes (1.0%)824612/824612 bytes (100.0%)
  Done
File saved as /home/docs/.imageio/images/stent.npz.

Display slice of the volume.

[17]:
iv = kplt.volview(vol, slice_axis=0, vmin_quantile=1e-2, cmap="viridis")
iv.set_volume_slice(128)

Display slice of the transposed volume with colorbar.

[18]:
iv = kplt.volview(vol.transpose((1, 2, 0)), slice_axis=0, cmap="viridis", show_cbar=True)
iv.set_volume_slice(110)

Plot slices of two different axes as subplots of the same figure. This is only feasible because the volume has the same dimensions on these two axes: plot axes should not be slice-shared across volume axes of different dimensions.

[19]:
fig, ax = kplt.subplots(nrows=1, ncols=2, sharex=True, sharey=True, figsize=(10, 8))
kplt.volview(vol, slice_axis=2, title="Axis 0-1 slices", vmin_quantile=1e-2, cmap="viridis",
             show_cbar=True, ax=ax[0]);
kplt.volview(vol, slice_axis=1, title="Axis 0-2 slices", vmin_quantile=1e-2, cmap="viridis",
             show_cbar=True, ax=ax[1]);
fem = kplt.figure_event_manager(fig, error=True)
fem.set_slice_share(ax)
fem.set_cmap_share(ax)
fem.get_axevman_for_axes(ax[0]).plot.set_volume_slice(100)
fig.show()