Statistical Plots#

Summaries of many neurons or trials call for the standard statistical graphics. This notebook uses them to answer typical questions about a recorded or simulated population:

Question

Function

How are firing rates distributed?

distribution_plot, qq_plot

How do conditions compare?

box_plot, violin_plot

How are several properties related?

scatter_matrix, correlation_matrix

Does one quantity predict another?

regression_plot, residual_plot

box_plot, violin_plot and distribution_plot take either a list of arrays (one per group) or a 2-D array of shape (samples, groups).

1. Setup#

import matplotlib.pyplot as plt
import numpy as np

import braintools

plt.rcParams["figure.dpi"] = 90
rng = np.random.default_rng(2)

2. Distributions of Firing Rates#

Firing rates across a population are typically right-skewed, close to log-normal. 400 simulated neurons:

rates = rng.lognormal(mean=np.log(4.0), sigma=0.8, size=400)     # Hz
print(f"mean {rates.mean():.2f} Hz, median {np.median(rates):.2f} Hz, max {rates.max():.1f} Hz")

fig, ax = plt.subplots(1, 2, figsize=(12, 3.8))
braintools.visualize.distribution_plot(rates, plot_type="both", bins=40, fit_normal=True, labels=["rates"],
                                       ax=ax[0], xlabel="Rate (Hz)", title="Raw rates")
braintools.visualize.distribution_plot(np.log10(rates), plot_type="both", bins=40, fit_normal=True,
                                       labels=["log10 rates"], ax=ax[1], xlabel="log10 rate", title="Log rates")
plt.tight_layout(); plt.show()
mean 5.41 Hz, median 4.00 Hz, max 39.0 Hz
../_images/1872cb9c0bb7577f75c6f3c353025e93ccff705259ac613acbd2fb6b6a91a2f8.png

plot_type selects a histogram ('hist'), a kernel density estimate ('kde') or both; fit_normal=True overlays the maximum-likelihood normal density. On the raw rates, the normal fit misses the peak and the long tail, and would put probability on negative rates; on the log rates it fits well.

A Q-Q plot makes the comparison sharper: it plots the sorted sample against the quantiles of a reference distribution at the plotting positions \((i - 0.5)/n\); a sample from that distribution lies on the dashed line (a least-squares line, so location and scale do not matter). distribution can be 'norm', 'uniform' or 'expon'.

isis = rng.exponential(0.1, 500)                       # intervals of a Poisson neuron
fig, ax = plt.subplots(1, 3, figsize=(15, 4.2))
braintools.visualize.qq_plot(rates, ax=ax[0], s=8, title="Raw rates vs normal")
braintools.visualize.qq_plot(np.log10(rates), ax=ax[1], s=8, title="log10 rates vs normal")
braintools.visualize.qq_plot(isis, distribution="expon", ax=ax[2], s=8, title="Poisson ISIs vs exponential")
plt.tight_layout(); plt.show()
../_images/f6cb632d2cd819d9df1ebf4ed05c201473803309fdecfca3f6da979dc9a20a9b.png

The raw rates bend away from the line in the upper tail (right skew); the log rates and the Poisson intervals follow their reference lines, with the usual scatter in the extreme tail.

3. Comparing Conditions#

Rates of 200 neurons under four conditions. In condition D, half of the neurons are suppressed and half are enhanced, so the distribution is bimodal:

base = rng.lognormal(np.log(5), 0.2, 200)
conditions = np.column_stack([
    base,                                                # A: baseline
    base * 1.5,                                          # B: uniform gain
    base + rng.normal(0, 2, 200),                        # C: added noise
    np.where(rng.random(200) < 0.5, 0.4, 1.8) * base,    # D: half suppressed, half enhanced
])
labels = ["A", "B", "C", "D"]
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
braintools.visualize.box_plot(conditions, labels=labels, ax=ax[0], ylabel="Rate (Hz)", title="Box plot",
                              colors=["C0", "C1", "C2", "C3"])
braintools.visualize.violin_plot(conditions, labels=labels, ax=ax[1], ylabel="Rate (Hz)", title="Violin plot",
                                 colors=["C0", "C1", "C2", "C3"])
plt.tight_layout(); plt.show()
print("medians:", np.round(np.median(conditions, axis=0), 2))
../_images/a6b28808f7ed550da2df02326e65368d8d21ff03e13787cb1bafb0f7719e2520.png
medians: [4.98 7.47 4.88 6.52]

The box plot shows median, quartiles, whiskers (1.5 × IQR) and, with showmeans=True (the default), the mean as a marker. For condition D it looks like a wide but ordinary distribution; the violin plot, a mirrored kernel density estimate, reveals the two groups. Box plots summarize, violin plots show shape, so plot the shape when distributions might be multimodal. notch=True adds a confidence interval for the median to box plots.

4. Relations Between Properties#

For each neuron we compute four properties from its spike train: firing rate, CV of the inter-spike intervals, the fraction of intervals shorter than 10 ms (a burst index), and the Fano factor of spike counts in 100 ms windows. Neurons are generated as gamma processes (regular to irregular) with some bursty ones.

def spike_train(rate, shape, burst_prob, T=20.0):
    isis = rng.gamma(shape, 1.0 / (shape * rate), int(3 * rate * T))
    isis = np.where(rng.random(isis.size) < burst_prob, rng.uniform(0.002, 0.008, isis.size), isis)
    t = np.cumsum(isis)
    return t[t < T]

props = []
for _ in range(150):
    rate, shape, burst = rng.uniform(2, 20), rng.choice([0.5, 1, 2, 4, 8]), rng.choice([0, 0, 0.3])
    t = spike_train(rate, shape, burst)
    isi = np.diff(t)
    counts = np.histogram(t, bins=np.arange(0, 20.01, 0.1))[0]
    props.append([len(t) / 20.0, isi.std() / isi.mean(), np.mean(isi < 0.01), counts.var() / counts.mean()])
props = np.array(props)
names = ["rate", "CV", "burst idx", "Fano"]

fig = braintools.visualize.scatter_matrix(props, labels=names, figsize=(8, 8), s=8)
plt.show()
../_images/b77bd25924b6c37dd694603ca0d5f713baf5fe607f14905ba40f30e957423658.png

scatter_matrix creates its own figure with all pairwise scatter plots and per-variable histograms on the diagonal, and returns the figure. CV and Fano factor are strongly related (for renewal processes the Fano factor approaches CV² for counting windows much longer than the mean interval; 100 ms windows are shorter, so the relation here is closer to linear), rate is nearly unrelated to both, and the bursty neurons form a separate cluster with a high burst index.

Correlation matrices quantify the relations. Pearson’s \(r\) measures linear association; Spearman’s \(\rho\) and Kendall’s \(\tau\) (method='spearman', 'kendall') are rank correlations and measure any monotonic association. For the properties above they agree closely. They differ when a relation is monotonic but strongly curved, as for a neuron whose rate grows exponentially with its input, here added as a fifth column next to the input:

drive = rng.uniform(0, 1, 150)
expo_rate = np.exp(5 * drive) + rng.normal(0, 3, 150)
data = np.column_stack([props, drive, expo_rate])
labels = names + ["input", "exp. rate"]
fig, ax = plt.subplots(1, 2, figsize=(13, 5))
for a, method in zip(ax, ["pearson", "spearman"]):
    braintools.visualize.correlation_matrix(data, labels=labels, method=method, ax=a, title=method.capitalize())
plt.tight_layout(); plt.show()
../_images/8b2ed918963e6e0d6019055311749be7ec6cdf1591e0c152700ea1ff479294e2.png

For input and exponential rate, Pearson’s \(r\) (0.86) is clearly lower than Spearman’s \( ho\) (0.94): the relation is monotonic, but far from a straight line. (The input column is unrelated to the spike-train properties, as it should be.)

5. Regression and Residuals#

The input–output curve of a neuron: rate as a function of input current, here a saturating curve measured with noise. regression_plot fits a straight line, reports \(R^2\) and shades the 95 % confidence band of the fitted mean, which is much narrower than the scatter of individual points. A high \(R^2\) does not mean the model is right; the residuals tell:

current = rng.uniform(0, 3, 150)
rate_obs = 60 * np.tanh(current / 1.5) + rng.normal(0, 3, 150)

fig, ax = plt.subplots(1, 3, figsize=(16, 4))
braintools.visualize.regression_plot(current, rate_obs, ax=ax[0], xlabel="Input current", ylabel="Rate (Hz)",
                                     title="Linear fit")
slope, intercept = np.polyfit(current, rate_obs, 1)
braintools.visualize.residual_plot(rate_obs, slope * current + intercept, ax=ax[1], title="Residuals: linear model")
# the right model: fit the tanh curve's amplitude and scale with a coarse grid search
grid = [(A, s) for A in np.linspace(40, 80, 81) for s in np.linspace(0.5, 3, 101)]
A, s = min(grid, key=lambda p: np.sum((rate_obs - p[0] * np.tanh(current / p[1])) ** 2))
braintools.visualize.residual_plot(rate_obs, A * np.tanh(current / s), ax=ax[2], title=f"Residuals: {A:.0f} tanh(I / {s:.2f})")
plt.tight_layout(); plt.show()
../_images/d8c5c08a67941249b637a0485b8719af19bee85142735391c136d35458d254e9.png

The linear fit has a high \(R^2\), yet its residuals form an arch: negative at both ends and positive in the middle, the signature of a missing curvature. The saturating model’s residuals scatter evenly around zero.

Summary#

  • distribution_plot (histogram, KDE, normal fit) and qq_plot show whether a sample follows a distribution; rates are often log-normal, so look at log rates.

  • box_plot summarizes and violin_plot shows shape; both accept a (samples, groups) array or a list of arrays.

  • scatter_matrix shows all pairwise relations; correlation_matrix quantifies them with Pearson (linear) or Spearman/Kendall (monotonic) correlations.

  • regression_plot shades the confidence band of the fitted mean; check the model with residual_plot, not with \(R^2\) alone.