Interactive Figures#
The interactive_* functions build Plotly figures: you can zoom, pan, hover over points to read exact values, and toggle traces in the legend. They return a plotly.graph_objects.Figure, which displays in Jupyter, can be modified with Plotly’s API, and can be saved as a stand-alone HTML file. Plotly is an optional dependency (pip install plotly).
Function |
Static counterpart |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
3-D plots |
|
a combined overview |
1. Setup and Data#
import numpy as np
import plotly.io as pio
import braintools
pio.renderers.default = "plotly_mimetype+notebook_connected" # load plotly.js from the CDN
rng = np.random.default_rng(4)
The same kind of data as in the first notebook: 40 neurons over 2 s, the first 20 responding to a stimulus at 0.5 s, the others firing regularly. Spike times in seconds.
T, dt = 2.0, 0.001
t_grid = np.arange(0, T, dt)
rate = 5.0 + 35.0 * (t_grid >= 0.5) * np.exp(-(t_grid - 0.5) / 0.1)
def regular(rate_hz=10.0, k=8):
t = np.cumsum(rng.gamma(k, 1.0 / (k * rate_hz), 60)) - rng.uniform(0, 0.1)
return t[(t >= 0) & (t < T)]
spikes = [t_grid[rng.random(t_grid.size) < rate * dt] for _ in range(20)] + [regular() for _ in range(20)]
times = np.concatenate(spikes)
ids = np.concatenate([np.full(len(s), i) for i, s in enumerate(spikes)])
print("spikes:", times.size)
spikes: 664
2. Spike Raster#
Hover over a spike to see its neuron and time; drag to zoom into the response. color_by colors spikes by 'neuron' or 'time'.
fig = braintools.visualize.interactive_spike_raster(spikes, color_by="neuron", title="Raster (hover, zoom)",
width=750, height=400)
fig.update_xaxes(title="Time (s)")
fig
Like spike_raster, it takes a list of trains or a flat time array with neuron_ids, plus time_range and neuron_range. The returned figure can be adjusted with Plotly’s methods, as update_xaxes above.
3. Time Series#
interactive_line_plot(x, ys, labels) draws several traces against a common x-axis; clicking a legend entry hides or shows a trace. Here, the population rate of each group, smoothed with a 20 ms window:
kernel = np.ones(20) / 20
binned = np.zeros((2, t_grid.size))
for g, sl in enumerate([slice(0, 20), slice(20, 40)]):
np.add.at(binned[g], np.minimum((np.concatenate(spikes[sl]) / dt).astype(int), t_grid.size - 1), 1)
group_rate = [np.convolve(b / 20 / dt, kernel, mode="same") for b in binned]
fig = braintools.visualize.interactive_line_plot(t_grid, group_rate, labels=["responsive", "regular"],
title="Group rates", xlabel="Time (s)", ylabel="Rate (Hz)",
width=750, height=350)
fig
4. Matrices#
interactive_heatmap shows any matrix with hover values; interactive_correlation_matrix computes and shows Pearson or Spearman correlations of (samples, variables) data. Below, the spike counts of the 40 neurons in 50 ms bins (neurons × time), and the correlations between the first 10 neurons, which share the stimulus-driven rate modulation:
edges = np.arange(0, T + 1e-9, 0.05)
counts = np.array([np.histogram(s, edges)[0] for s in spikes]) # (neurons, bins)
fig = braintools.visualize.interactive_heatmap(counts, x_labels=[f"{e:.2f}" for e in edges[:-1]],
y_labels=[f"n{i}" for i in range(40)],
title="Spike counts per 50 ms bin", width=750, height=500)
fig
fig = braintools.visualize.interactive_correlation_matrix(counts[:10].T, labels=[f"n{i}" for i in range(10)],
method="spearman", title="Spearman correlations",
width=550, height=500)
fig
5. Distributions#
interactive_histogram overlays several data sets with a common set of bins, so bar heights are directly comparable. ISI distributions of the two groups:
isi_resp = np.concatenate([np.diff(s) for s in spikes[:20]])
isi_reg = np.concatenate([np.diff(s) for s in spikes[20:]])
fig = braintools.visualize.interactive_histogram([isi_resp, isi_reg], labels=["responsive (Poisson)", "regular"],
bins=60, title="Inter-spike intervals", xlabel="ISI (s)",
width=750, height=380)
fig
6. Networks#
interactive_network draws a graph on a circular layout (or at given positions); hovering over an edge shows its weight when edge_weights is given, which also sets the line widths. As in network_topology, every non-zero entry is an edge, negative ones blue.
n = 12
W = (rng.random((n, n)) < 0.25) * rng.lognormal(-0.5, 0.4, (n, n))
np.fill_diagonal(W, 0)
W[9:] = -2 * W[9:] + 0.0 # neurons 9-11 are inhibitory
fig = braintools.visualize.interactive_network(W, edge_weights=W, node_labels=[f"{'I' if i >= 9 else 'E'}{i}" for i in range(n)],
node_colors=np.r_[np.zeros(9), np.ones(3)],
title="Hover over edges for weights", width=600, height=550)
fig
7. Three-Dimensional Views#
interactive_3d_scatter and interactive_surface can be rotated with the mouse. Neurons placed in a cortical column, colored by depth-dependent firing rate, and a 2-D rate map as a surface:
xyz = rng.uniform([0, 0, 0], [0.3, 0.3, 1.0], (300, 3)) # mm; z = cortical depth
depth_rate = 2 + 18 * np.exp(-(xyz[:, 2] - 0.4) ** 2 / (2 * 0.1 ** 2)) + rng.exponential(1, 300)
fig = braintools.visualize.interactive_3d_scatter(xyz[:, 0], xyz[:, 1], xyz[:, 2], color=depth_rate,
size=np.full(300, 4), title="Rate by position (layer 4 at 0.4 mm)",
width=650, height=550)
fig
gx, gy = np.meshgrid(np.linspace(0, 1, 40), np.linspace(0, 1, 40))
rate_map = 15 * np.exp(-((gx - 0.6) ** 2 + (gy - 0.4) ** 2) / (2 * 0.12 ** 2))
fig = braintools.visualize.interactive_surface(rate_map, x=gx[0], y=gy[:, 0], title="Place field as a surface",
width=650, height=550)
fig
8. A Dashboard#
dashboard_neural_activity combines a raster, the ISI distribution (intervals computed within each neuron), per-neuron firing rates, a population-activity trace and summary statistics in one figure. It takes flat spike times with neuron_ids (or a list of trains) and, optionally, a population-activity array with its time axis:
fig = braintools.visualize.dashboard_neural_activity(times, neuron_ids=ids, population_activity=group_rate[0],
time=t_grid, title="Overview", width=1000, height=700)
fig
9. Saving#
Plotly figures save as stand-alone HTML files that keep the interactivity (fig.write_html("raster.html")), or as static images with fig.write_image(...), which needs the separate kaleido package.
Summary#
The
interactive_*functions return Plotly figures with zoom, pan, hover and legend toggling; adjust them with Plotly’s API.They mirror the static functions: spike rasters from trains or
(times, neuron_ids), line plots, heatmaps and correlation matrices, histograms with shared bins, signed networks with hoverable weights, 3-D scatter plots and surfaces.dashboard_neural_activitygives a one-call overview of spiking data.Save with
fig.write_html(...)to share interactive figures.