Plotting

Setup: install HyperTools (run this cell first on Colab)
[ ]:
# HyperTools setup: use 1.1 or newer; retain a current local checkout.
import importlib.util
from importlib.metadata import version, PackageNotFoundError
from packaging.version import Version
from pathlib import Path
try:
    _hypertools_version = Version(version('hypertools'))
except PackageNotFoundError:
    _hypertools_version = Version('0')
if _hypertools_version < Version('1.1.0'):
    _spec = importlib.util.find_spec('hypertools')
    if _spec and _spec.origin and (Path(_spec.origin).resolve().parents[1] / '.git').exists():
        raise RuntimeError('Select a HyperTools 1.1 checkout/kernel before running this tutorial; the installer will not replace your checkout.')
    %pip install -q "hypertools[interactive]>=1.1.0"
else:
    print('Keeping HyperTools', _hypertools_version, 'in this kernel. Optional extras are loaded when requested.')

Nearly all of the hypertools functionality may be accessed through the main plot function. This design enables complex data analysis, data manipulation, and plotting to be carried out in a single function call. To use it, simply pass your samples-by-features dataset(s) [in the form of a numpy array, pandas DataFrame, or (mixed) list] to the plot function. Let’s explore!

This tutorial walks through hyp.plot one keyword at a time: formats and dimensions, dimensionality reduction, coloring (hue, names, colorbar, alpha), camera and labels, clustering, normalization and alignment, missing data (impute) and resample, animation, the plotly backend, saving, and the exceptions hypertools raises.

Import Hypertools and other libraries for tutorial

[1]:
import hypertools as hyp
import numpy as np
import pandas as pd

%matplotlib inline

Load your data

We will load one of the sample datasets. This dataset consists of 8,124 samples of mushrooms with various text features.

[2]:
mushrooms = hyp.load('mushrooms')

We can peek at the first few rows of the dataframe using the pandas function head().

[3]:
mushrooms.head()
[3]:
bruises cap-color cap-shape cap-surface gill-attachment gill-color gill-size gill-spacing habitat odor ... ring-type spore-print-color stalk-color-above-ring stalk-color-below-ring stalk-root stalk-shape stalk-surface-above-ring stalk-surface-below-ring veil-color veil-type
0 t n x s f k n c u p ... p k w w e e s s w p
1 t y x s f k b c g a ... p n w w c e s s w p
2 t w b s f n b c m l ... p n w w c e s s w p
3 t w x y f n n c u p ... p k w w e e s s w p
4 f g x s f k b w g n ... e n w w e t s s w p

5 rows × 22 columns

Plot with default settings

Hypertools can plot your high-dimensional data quickly and easily with little user-generated input. By default, hypertools automatically reduces your data via incremental principal component analysis (if dimensions > 3) and plots a 3D line plot where the axes represent the top 3 principal components of the dataset.

[4]:
fig = hyp.plot(mushrooms) # plots a line
../_images/tutorials_plot_9_0.png

By default, hypertools assumes you are passing in a timeseries, and so it plots a trajectory of the data evolving over time. If you aren’t visualizing a timeseries, you can instead plot the individual observations as dots or other symbols by specifying an appropriate format style.

To show the individual points, simply pass the '.' format string in the second argument position, or in any position using fmt='.'; the format string is parsed by matplotlib.

[5]:
fig = hyp.plot(mushrooms, '.') # plots dots
../_images/tutorials_plot_11_0.png
[6]:
fig = hyp.plot(mushrooms, fmt='b*') # plots blue asterisks
../_images/tutorials_plot_12_0.png

Plot in 2D

We can also opt to plot high dimensional data in two dimensional space, rather than 3D, by passing the ndims argument.

[7]:
fig = hyp.plot(mushrooms, '.', ndims=2)
../_images/tutorials_plot_14_0.png

Using other dimensionality reduction algorithms

To explore a data reduction method aside from the default (PCA), use the reduce argument. Here, we pass the reduce argument a string.

Other supported reduction models include: PCA, IncrementalPCA, SparsePCA, MiniBatchSparsePCA, KernelPCA, FastICA, FactorAnalysis, TruncatedSVD, DictionaryLearning, MiniBatchDictionaryLearning, TSNE, Isomap, SpectralEmbedding, LocallyLinearEmbedding, MDS, UMAP, and the torch autoencoders (see the reduce tutorial).

SparsePCA (below) finds components whose loadings are mostly zero, so each plotted axis is driven by a handful of the original features instead of a dense mixture of all of them. That usually makes the axes easier to interpret, at the cost of no longer maximizing the variance explained.

[8]:
fig = hyp.plot(mushrooms, '.', reduce='SparsePCA')
../_images/tutorials_plot_16_0.png

Parameter Specifications

For finer control of the parameters, you can pass the reduce argument a dictionary with the keys model and kwargs (see scikit-learn documentation about parameter options for specific reduction techniques).

Below, whiten=True rescales each component to unit variance, so the plotted axes have equal spread rather than the first principal component dominating the range. The shape of the point cloud is preserved; the relative scale of the axes is not.

[9]:
fig = hyp.plot(mushrooms, '.', reduce={'model': 'PCA', 'kwargs': {'whiten': True}})
../_images/tutorials_plot_18_0.png

Coloring by hue

To color your datapoints by group labels, pass the hue argument. It accepts strings, ints, and floats, or a list of these. You must pass hue the same number of labels as you have rows in your data matrix.

Here, we split the rows into five roughly equal-sized groups using np.array_split, which distributes any remainder so that the number of labels exactly matches the number of rows (8,124 is not divisible by 5). Note that we pass ints, strings, floats, and None in the same list to the hue argument.

[10]:
groups = [1, 'two', 3.0, None, 'four']
sizes = [len(chunk) for chunk in np.array_split(np.arange(mushrooms.shape[0]), len(groups))]
hue = [group for group, size in zip(groups, sizes) for _ in range(size)]
fig_group = hyp.plot(mushrooms, '.', hue=hue)
../_images/tutorials_plot_20_0.png

Adding a legend

When coloring, you may want a legend to indicate group type. Passing legend=True will generate the legend based on your groupings.

[11]:
fig_hue = hyp.plot(mushrooms, '.', hue=hue, legend=True)
../_images/tutorials_plot_22_0.png

Naming datasets with names

hue colors observations; names labels datasets. When you pass a list of datasets, names=[...] (one entry per dataset) names each trace and turns the legend on. Below we split the mushrooms into three consecutive blocks of rows and name them; the blocks are drawn as three separate datasets, each with its own color and legend entry.

[12]:
blocks = np.array_split(hyp.tools.df2mat(mushrooms), 3)
fig_names = hyp.plot(blocks, '.', names=['first third', 'second third', 'last third'])
../_images/tutorials_plot_24_0.png

Continuous hue and a colorbar

hue can also be a continuous value per observation (here, the row index). The points are then colored along a colormap, and colorbar=True (or a dict with a label) draws the matching colorbar so the reader can map colors back to values.

[13]:
row_position = np.arange(mushrooms.shape[0], dtype=float)
fig_cbar = hyp.plot(mushrooms, '.', hue=row_position, palette='viridis',
                    colorbar={'label': 'row index'},
                    title='Mushrooms colored by row position')
../_images/tutorials_plot_26_0.png

A data matrix as a palette

A palette does not have to be a colormap name or a list of colors: a t x k data matrix (a numpy array, nested list or DataFrame) works too. hyp.plot reduces it to three dimensions with hyp.reduce (palette_reduce=, default 'PCA'; palette_manip=, palette_normalize= and palette_align= are passed through to the reducer), scales each reduced column to [0, 1] and reads it as an RGB channel, sorts the rows (palette_sort=, default 'columns': along the first component) and resamples the result by interpolation to however many colors the plot needs – one per dataset, one per category, or a gradient along a continuous hue. Below, a random walk is mixed into twelve noisy columns and that matrix colors the walk: the three directions of greatest variance in the matrix become the red, green and blue channels.

The same ordering applies to colors extracted from an image with palette='image:<path>'. image_palette (in hypertools.plot.colors) lists them most salient first (and that is still the color a dataset leads with when an image stands for one dataset), but as a plot palette they are sorted by value, dark to bright, so a gradient reads as one. palette_sort= (or ?sort= inside the spec) chooses 'value', 'hue', 'lightness', 'columns' or 'original' for image and matrix palettes alike. A 2-D array with 3 or 4 columns whose values all lie in [0, 1] is still read as a list of colors.

[14]:
rng = np.random.default_rng(0)
walk = np.cumsum(rng.normal(size=(200, 3)), axis=0)                             # a 3-D random walk
weights = walk @ rng.normal(size=(3, 12)) + 0.5 * rng.normal(size=(200, 12))    # mixed into a 200 x 12 matrix
fig_matrix = hyp.plot(walk, hue=np.arange(len(walk)), palette=weights,
                      colorbar={'label': 'time step'},
                      title='A 200 x 12 data matrix as the palette')
../_images/tutorials_plot_28_0.png
[15]:
fig_ica = hyp.plot(walk, hue=np.arange(len(walk)), palette=weights,
                   palette_reduce='FastICA', palette_sort='hue',
                   colorbar={'label': 'time step'},
                   title="palette_reduce='FastICA', palette_sort='hue'")
../_images/tutorials_plot_29_0.png

Per-dataset transparency with alpha

alpha accepts one opacity for every dataset or a list with one value per dataset. Fading the backdrop datasets and leaving one opaque is an easy way to highlight it.

[16]:
fig_alpha = hyp.plot(blocks, '.', alpha=[0.1, 0.1, 1.0],
                     names=['first third (faded)', 'second third (faded)', 'last third'],
                     title='alpha=[0.1, 0.1, 1.0] highlights the last block')
../_images/tutorials_plot_31_0.png

Figure size, camera angle, axis labels and fonts

size=[width, height] sets the figure size in inches. For 3D plots, elev (degrees above the x-y plane) and azim (rotation about the z axis) position the camera, exactly as in matplotlib’s Axes3D.view_init. xlabel/ylabel/zlabel label the axes, and font sets the typeface for every text surface hypertools draws (title, legend, colorbar, labels). By default hypertools renders text in the Noto Sans face it bundles; font='DejaVu Serif' switches to the serif face that ships with matplotlib.

[17]:
fig_camera = hyp.plot(blocks, '.', names=['first third', 'second third', 'last third'],
                      size=[7, 5], elev=35, azim=120,
                      xlabel='PC 1', ylabel='PC 2', zlabel='PC 3',
                      font='DejaVu Serif',
                      title='elev=35, azim=120, serif font')
../_images/tutorials_plot_33_0.png

Labeling plotted points

The labels argument accepts a list of labels for each point, which must be the same length as the data (the number of rows). If no label is wanted for a particular point, simply input None. In this example, we have made use of None in order to label only three points of interest (the first, second, and last in our set).

Each label sits on a translucent white box; label_alpha sets that box’s opacity (the default is 0.5). Setting it to 1 makes the boxes fully opaque so the text is readable over a dense cloud.

[18]:
num_unlabeled = int(mushrooms.shape[0]) - 3
labeling = ['a', 'b'] + [None] * num_unlabeled + ['c']
fig_labeled = hyp.plot(mushrooms, '.', labels=labeling, label_alpha=1.0)
../_images/tutorials_plot_35_0.png

Data Clustering

Hypertools can also auto-cluster your datapoints with the n_clusters argument. To implement, simply set n_clusters to an integer.

Clustering runs on the reduced coordinates, and the cluster assignment is used purely as a color: with n_clusters=6 the same 8,124 points are split across six colored series, and each point stays exactly where it was plotted without n_clusters.

[19]:
fig_cluster = hyp.plot(mushrooms, '.', n_clusters=6)
../_images/tutorials_plot_37_0.png

Normalization

For quick, easy data normalization of the input data, pass the normalize argument.

You can pass the following arguments as strings:

  • across - columns z-scored across lists (the default of hyp.normalize; hyp.plot does not normalize unless asked)

  • within - columns z-scored within each list

  • row - each row z-scored

within and across differ only when you pass more than one dataset: for a single array or DataFrame there is nothing to pool across, so both z-score the same columns and return exactly the same result. To make the difference real, we split the mushroom data into two halves below and normalize the pair. With within, each half’s columns are z-scored using that half’s own mean and standard deviation.

[20]:
mushroom_mat = hyp.tools.df2mat(mushrooms)
half = mushroom_mat.shape[0] // 2
mushroom_halves = [mushroom_mat[:half], mushroom_mat[half:]]

fig_norm = hyp.plot(mushroom_halves, '.', normalize='within')
../_images/tutorials_plot_39_0.png

Aligning datasets with different coordinate systems

You can also align multiple datasets using the hypertools plot function in order to visualize data in a common space. This is useful if you have more than one high-dimensional dataset that is related to the same thing. For example, consider a brain imaging (fMRI) dataset comprised of multiple subjects watching the same movie. Voxel A in subject 1 may not necessarily be Voxel A in subject 2. Alignment finds the rotation that brings the datasets into register.

To do so, pass one of the following to the align argument:

Below is a simple example of a spiral: two copies of the same curve in different coordinate systems. The align tutorial covers each algorithm in more depth.

[21]:
data_spiral = hyp.load('spiral')
fig_before = hyp.plot(data_spiral, ['-', '--'], title='Before alignment')

# align the data with plot's `align` argument, using Procrustes to rotate the
# first dataset onto the second (index=1)
fig_aligned = hyp.plot(data_spiral, ['-', '--'],
                       align={'model': 'Procrustes', 'kwargs': {'index': 1}},
                       title='After alignment')
../_images/tutorials_plot_41_0.png
../_images/tutorials_plot_41_1.png

Missing data

Missing data points? No problem! hypertools fills missing values (NaNs) before reducing, using probabilistic principal components analysis (PPCA) by default. Here, we generate a small synthetic random walk, remove 5% of its cells with hypertools.tools.damage (chosen without replacement, from a seeded generator so the figure is reproducible), and plot the full and the damaged copies together. The observed values are left untouched; only the NaN cells are reconstructed, so the two trajectories should nearly coincide.

hypertools.tools.missing_inds reports which rows contained a NaN, so we can overplot just those rows (as '*') and see how close the inferred values landed to the original data. The reduction is shared across the three datasets, so the marked points sit exactly on the imputed trajectory.

[22]:
from scipy.linalg import toeplitz

rng = np.random.default_rng(0)
K = 10 - toeplitz(np.arange(10))
full = np.cumsum(rng.multivariate_normal(np.zeros(10), K, 250), axis=0)

# remove 5% of the cells, without replacement
damaged, mask = hyp.damage(full, frac=0.05, seed=rng, return_mask=True)
n_missing = int(mask.sum())
print(f'{n_missing} of {damaged.size} cells set to NaN '
      f'({mask.any(axis=1).sum()} of {len(damaged)} rows touched)')

# reduce the pair together (PPCA fills the NaNs first), then mark the rows that were filled
full_r, damaged_r = hyp.reduce([full, damaged], ndims=3)
filled_rows = hyp.tools.missing_inds(damaged)

fig_nan = hyp.plot([full_r, damaged_r, damaged_r[filled_rows]], ['-', '--', '*'],
                   reduce=None, legend=['Full', 'Missing (PPCA-filled)', 'Filled rows'])
125 of 2500 cells set to NaN (104 of 250 rows touched)
<cell>:14: UserWarning: Missing data: filling missing values with PPCA (observed values are preserved exactly; only the NaN entries are reconstructed). Pass impute= to choose a different imputation model -- see hypertools.impute.
  full_r, damaged_r = hyp.reduce([full, damaged], ndims=3)
../_images/tutorials_plot_43_2.png

Choosing the imputer with impute

PPCA reconstructs each missing cell from the other columns of the same row, so it has nothing to condition on when an entire row is missing – it warns and leaves such rows NaN, and the reduction then fails on them. For a timeseries, a Kalman smoother instead uses the neighboring rows, so it bridges whole-row gaps. impute='Kalman' swaps the imputer inside plot; any hypertools.impute model name works ('KNNImputer', 'IterativeImputer', 'SimpleImputer', …), and the projectile tutorial compares them. Below we blank out five consecutive rows entirely with hyp.damage(..., rows=slice(100, 105)) and let the Kalman smoother fill them.

[23]:
gap = hyp.damage(damaged, frac=0, rows=slice(100, 105))   # five fully-missing rows on top of the scattered NaNs

fig_impute = hyp.plot([full, gap], ['-', '--'], impute='Kalman',
                      legend=['Full', 'Gap (Kalman-filled)'],
                      title="impute='Kalman' bridges five fully-missing rows")
../_images/tutorials_plot_45_0.png

Resampling trajectories with resample

resample=N interpolates every dataset to exactly N rows (PCHIP, via the Resample manipulator) before the normalize / reduce / align pipeline. Coarsening the 250-row walk to 40 rows keeps its overall shape while dropping the wiggles; the same call with manip={'model': 'Resample', 'kwargs': {'n_samples': 40}} produces identical values. The two panels use different resample= values on the same data rather than one shared pipeline fit across datasets, so panels= (one dataset per panel, one shared fit) does not apply here; we draw each into its own 3D axes instead, with hyp.subplots (a thin wrapper over plt.subplots that pre-sets the 3-D projection) plus ax=.

[24]:
# backend='matplotlib' on the grid and on each call: fig.tight_layout() is matplotlib's,
# and on Colab the default backend would be plotly
fig, axes = hyp.subplots(1, 2, size=[11, 4.5], backend='matplotlib')
hyp.plot(full, '-', ax=axes[0], title='250 rows', backend='matplotlib', show=False)
hyp.plot(full, '-o', resample=40, ax=axes[1], title='resample=40', backend='matplotlib', show=False)
fig.tight_layout()
../_images/tutorials_plot_47_0.png

Animating

Any plot becomes an animation with animate=True (a trajectory that draws itself in while the camera rotates; 'spin', 'serial', 'window' and 'morph' are the other styles – see the animation guide). duration and frame_rate set the length and smoothness. With save_path= the animation is encoded to a file (.gif needs nothing extra; .mp4 needs FFmpeg) and show=False keeps the notebook from also embedding a live copy. The returned HyperAnimation exposes the finished figure as .figure. (On Colab the default backend is plotly, whose animations are plotly figures; backend='matplotlib' asks for the matplotlib HyperAnimation this cell uses.)

[25]:
anim = hyp.plot(full, animate=True, duration=6, frame_rate=15, backend='matplotlib',
                title='A random walk, animated', save_path='plot.mp4', show=False)
print(f'{anim.n_frames} frames written to plot.mp4')
display(anim.figure)

# Colab serves output frames separately from kernel files; embed movie bytes.
try:
    from google import colab as colab
except ImportError:
    pass  # Local Jupyter/Sphinx uses the relative video below.
else:
    from IPython.display import Video, display
    display(Video('plot.mp4', embed=True))

90 frames written to plot.mp4
../_images/tutorials_plot_49_1.png

Download the clip

Interactive plots with the plotly backend

hypertools draws with matplotlib by default (and with plotly automatically on Google Colab and Kaggle). backend='plotly' renders a single call with plotly instead, returning a plotly Figure you can rotate and zoom in the browser. hyp.set_interactive_backend('plotly') switches every subsequent plot; 'auto' restores the default. The same keywords (hue, names, labels, font, title, …) work on both backends.

[26]:
import plotly.io as pio
pio.renderers.default = 'notebook_connected'   # embed plotly figures in the saved notebook

subset = mushrooms.iloc[::8]   # ~1,000 points keeps the embedded figure small
fig_plotly = hyp.plot(subset, '.', hue=hue[::8], legend=True, backend='plotly',
                      title='mushrooms, rendered by plotly')

hyp.set_interactive_backend makes the switch for every plot that follows: the next figure is plotly without a backend= keyword on the call.

[27]:
hyp.set_interactive_backend('plotly')
fig_plotly2 = hyp.plot(subset, '.', n_clusters=4, title='set_interactive_backend: plotly')

hyp.set_interactive_backend('auto') restores the default choice (matplotlib here), and the same call now returns a matplotlib figure. Note the drag-to-rotate handle on the plotly figures above versus the static image below.

[28]:
hyp.set_interactive_backend('auto')        # ...and back to the default
fig_mpl = hyp.plot(subset, '.', n_clusters=4, title='back to matplotlib')
../_images/tutorials_plot_56_0.png

Saving

To save a plot created with hypertools, simply pass the save_path argument; the extension picks the format (any matplotlib savefig format for static plots, .gif/.mp4/… for animations, .html for plotly). Below we write the same figure as a .png and a .pdf into a temporary directory.

hyp.save is the companion for data: it writes an array or DataFrame in the format its extension names (.csv, .npy, .npz, .json, .parquet, .mat, .xlsx, or a pickle for anything else), and hyp.load reads it back. Saving the reduced coordinates is a cheap way to hand a plot’s data to another tool.

[29]:
import os
import tempfile

outdir = tempfile.mkdtemp()
for ext in ('png', 'pdf'):
    hyp.plot(mushrooms, '.', n_clusters=6, save_path=os.path.join(outdir, f'clusters.{ext}'),
             show=False)

# the reduced 3-D coordinates, as a CSV another tool can read
coords = hyp.reduce(mushrooms, ndims=3)
hyp.save(pd.DataFrame(coords, columns=['PC1', 'PC2', 'PC3']), os.path.join(outdir, 'coords.csv'))
reloaded = hyp.load(os.path.join(outdir, 'coords.csv'))

for name in sorted(os.listdir(outdir)):
    print(f'{name}: {os.path.getsize(os.path.join(outdir, name)) / 1e3:.0f} kB')
print('reloaded coordinates:', reloaded.shape, '-- identical:', np.allclose(reloaded.values, coords))
clusters.pdf: 125 kB
clusters.png: 35 kB
coords.csv: 473 kB
reloaded coordinates: (8124, 3) -- identical: True

What goes wrong, and how it is reported

hypertools raises HypertoolsError subclasses for its own failures: HypertoolsIOError when data cannot be loaded or saved (it is also an OSError, so existing except OSError handlers catch it), and HypertoolsBackendError for backend problems. Argument mistakes raise the standard ValueError/TypeError with a message naming the keyword. Two examples: loading a file that does not exist, and asking an animation to draw into a supplied ax (an animation owns its own figure, so that combination is refused rather than drawing somewhere you are not looking).

[30]:
import matplotlib.pyplot as plt

try:
    hyp.load('no_such_file.csv')
except hyp.HypertoolsIOError as e:
    print('HypertoolsIOError:', str(e).splitlines()[0])

fig, ax = plt.subplots()
try:
    hyp.plot(full, animate=True, ax=ax, backend='matplotlib')
except ValueError as e:
    print('ValueError:', str(e).splitlines()[0])
plt.close(fig)
HypertoolsIOError: could not load 'no_such_file.csv'. Tried, in order:
ValueError: ax= cannot be combined with animate=: an animated plot owns its own figure, so the axes you passed would be left empty and the animation drawn somewhere else. Drop ax= and use the returned animation's .figure (or .figure.axes[0]) to style what was drawn; for several panels in one animation, lay the panels out in the data and make a single plot call.

Plotting text using semantic models

In addition to numerical data, hypertools supports the plotting of text data by fitting the data to a semantic model. To keep this example quick to run, we’ll use a small list of sample sentences written in the style of State of the Union addresses. (The hosted text corpora – including the complete set of State of the Union addresses from 1989-2017 – and modern sentence-transformer embeddings are covered in the text tutorial and the Hugging Face embeddings tutorial.)

[31]:
sample_sotus_speeches = [
    "Tonight I can report to the nation that America is stronger and more secure.",
    "We gather tonight knowing that this generation has been tested by crisis.",
    "As we work together to advance America's interests, we must recognize threats.",
    "Education is the great equalizer in America for all our children."
]

By default, the text data will be transformed using a Latent Dirichlet Allocation model trained on a sample of Wikipedia pages. Simply pass the list of text data to the plot function, and under the hood it will be transformed to a topic vector and then reduced for plotting.

[32]:
fig = hyp.plot(sample_sotus_speeches)
../_images/tutorials_plot_64_0.png