From data to plot

Multi-peak 2D Gaussian fitting on heat maps

Fitting a single 2D Gaussian captures one isolated mode; fitting many overlapping peaks on a heat map is an inverse deconvolution problem with 6K+1 coupled parameters across a shared baseline offset. When two peaks sit within a few widths of each other or differ in amplitude, naive optimization merges components onto the brightest feature, flips (σx,σy) modulo π/2, or leaves weaker satellites missing inside high iso-contour thresholds.

Updated · 8 min read

On this page
  1. Why multi-peak 2D Gaussian fits collapse or swap labels
  2. How spatial seeding and local moments prevent peak collapse
  3. Reading contours and resolving more than six peaks
  4. Comparing Autoplot, OriginPro, SciPy, and GaussianMixture EM
  5. Multi-peak 2D Gaussian fitting in Autoplot
  6. Frequently asked questions

Why multi-peak 2D Gaussian fits collapse or swap labels

In an additive 2D mixture of K rotated Gaussians over a single shared background offset, the model surface is:

z(x,y)=offset+∑k=1KAkexp(−12[(xrot,kσx,k)2+(yrot,kσy,k)2])

where local rotated coordinates (xrot,k,yrot,k) rotate (x−x0,k,y−y0,k) by angle θk∈[−π,π]. Going from 1 to 6 peaks pushes the parameter count from 7 to 37, introducing three numerical failure modes absent in single-peak fits:

  1. Mode collapse during Trust Region steps: if two initial guesses sit too close or share global moments on a broad plateau, bounded least squares (scipy.optimize.curve_fit) slides both centroids onto the dominant maximum, producing twin nearly identical peaks or one ultra-wide background hump.
  2. Axis-permutation ambiguity (σx vs σy): whenever θk∈[−π,π] is unconstrained relative to major vs minor axes, rotating θk by ±π/2 and exchanging σx,k and σy,k yields the exact same ellipse—and as σx,k→σy,k (nearly circular peaks), the standard error on θk diverges.
  3. Under-represented secondary populations: as Stutzki and Guesten (1990) demonstrated in multi-Gaussian clump decomposition, a faint component overlapping a bright neighbor's wing requires local peak isolation so residual curvature drives its centroid rather than widening the neighbor.

For single-peak vs custom-formula models (Gaussian Peak, Lorentzian Peak, Mexican Hat) and Joint Density vs Scalar Field normalization rules, start with 2D surface and joint density fitting.

Autoplot 2D Density Fit overlay on a 68 by 68 Viridis Joint Density heat map showing four tilted elliptical Gaussian populations with fitted white contour ellipses at Fraction of Peak levels 0.16, 0.34, 0.56, and 0.78, white principal-axis center cross markers on all four peaks, and a vertical Density colorbar up to 3.41E-01
A 4-peak 2D Gaussian mixture fit (Fraction of Peak contours at 0.16, 0.34, 0.56, and 0.78 plus principal-axis center crosses) resolves all four unequal rotated modes cleanly on one Joint Density grid.

How spatial seeding and local moments prevent peak collapse

Greedy "highest-bin-first" seeding fails whenever one broad bright peak spans dozens of adjacent bins: picking the top K grid cells clusters every initial guess on that same hill. Autoplot (_gaussian_mixture_initial_centers and fit_gaussian_2d_mixture) avoids collapse through a three-stage spatial initialization before calling scipy.optimize.curve_fit (Branch et al. 1999):

  1. Deduplication radius from 8-neighbor grid spacing: excess weight wi=max(0,zi−zmin) pairs with a scipy.spatial.cKDTree over finite binned cell centers (xi,yi). Eight-nearest-neighbor median spacing sets a local-maximum window radius clamped to [0.03, 0.18] of the domain diagonal and a minimum center separation 0.5 * radius.
  2. Separated local maxima before deterministic fallback: candidate centers are scanned in descending weight order, accepting local maxima inside radius that satisfy the separation bound; if the surface is smooth and holds fewer than K strict local maxima, a deterministic pass fills remaining seeds from well-separated high-weight cells.
  3. Radius-clipped local moments per peak: instead of seeding widths from global variance across the whole map, each peak k computes weighted moments (x¯k,y¯k,sx,k,sy,k) inside a neighborhood capped at min(0.18 * diag, 0.5 * min_other_distance) and initializes θk=0 before running up to 60,000 bounded Trust Region Reflective evaluations, then sorts returned peaks (Peak 1, Peak 2, …) by descending amplitude Ak.

Just as in 1D multi-peak fitting and peak deconvolution, watch component errors and widths together: if any peak drifts to the edge of a cluster with inflated standard errors, decrease Peaks or isolate sub-clusters rather than forcing a higher K.

Autoplot Results block for 2D Density Fit with peaks=4 showing 2D Gaussian (Multi-Peak), R² = 0.9937, shared background offset 0.0002732 ± 4.37e-05, and sorted Peak 1 through Peak 4 parameter blocks with amplitude, x0, y0, σx, σy, θ, standard errors, and Export Fit Function
Fitted mixture outputs sorted by descending amplitude A (0.3198 down to 0.1582). Notice Peak 2 swapped (σx, σy) = (0.2804, 0.4933) at θ = -0.5359 rad—equivalent modulo π/2 to a wider σx at +1.035 rad.

Reading contours and resolving more than six peaks

Inspecting a multi-peak heat map only by its color scale hides amplitude differences and overlaps. Tune three controls in Visual and Range so smaller subpopulations remain legible:

  • Why default Sigma contours miss weak peaks: both Sigma (1σ,2σ,...) and Fraction of Peak compute contour z-levels relative to the single tallest component maxkAk (offset+Amaxexp(−k2/2) and offset+Amax·f). A secondary peak with A4=0.45A1 never even reaches a 1σ contour at 0.6065A1+offset! Switch Levels to Fraction of Peak with explicit low fractions (such as 0.16, 0.34, 0.56, 0.78), raise σ levels (1…3 or 1…4), or enter exact physical Z Value thresholds alongside Center marker crosses.
  • Splitting dense fields (K > 6) with Use ROI: built-in mixture fitting caps at Peaks = 6 (37 free parameters) to stay well-conditioned on gridded arrays. If your heat map contains 8 or 12 hotspots, build the source map once, toggle Use ROI (xmin, xmax, ymin, ymax) in Range to fit subsets of 2–6 nearby peaks inside local rectangles (filtering happens post-binning in data units), or switch to Custom Density Fit / Custom Surface Fit with explicit multi-Gaussian formulas and hand-entered initial guesses.
  • Checking grid resolution bias (Cells X, Cells Y): coarse grids flatten sharp peak cores (Cheezum et al. 2001), while overly thin grids violate the max(40, 25 * Peaks) finite-cell minimum inside tight ROI boxes. Keep Density normalization on for point clouds and verify that fitted centroids and widths hold steady across two nearby bin resolutions—see how to make a scientific heat map.

Comparing Autoplot, OriginPro, SciPy, and GaussianMixture EM

Choose between binned nonlinear least squares and unbinned expectation–maximization based on whether your data live on a gridded intensity surface or raw point coordinates:

WorkflowData representationMax peaks & seedingParameter units & strengths
Autoplot 2D Density Fit / Surface FitBinned finite grid cells (Density or Scalar Field)2–6 auto cKDTree peaks (ROI for larger clusters)Unnormalized amplitudes Ak, shared offset, ± stderr, interactive contours
OriginPro (nlfit2d / Peak Analyzer 2D)Matrix / XYZ worksheetReplicable Gauss2D replicas; manual or grid guessesShared parameter bounds, weights, Windows batch worksheets
SciPy curve_fit (custom script)User grid arraysArbitrary K; user supplies p0 and boundsFull control over parameter tying (σx,1=σx,2), residual weights
scikit-learn GaussianMixture (EM)Unbinned raw (X,Y) pointsArbitrary K; k-means++ initializationProbability weights ∑πk=1 and full covariance Σk; no grid bias, no offset

Use scikit-learn GaussianMixture when clustering unbinned (X,Y) events with zero background floor (offset = 0) and normalized mixture weights, or when you need BIC scans across K = 1…20. Use Autoplot when fitting directly to either measured 2D scalar surfaces (Z images/scans) or smooth joint-density grids with background offset, rotated principal axes, visual contour overlays, and exported gridded surfaces (Export Fit Surface). For coupled bounds and degeneracy checks across custom formulas, see nonlinear curve fitting.

In Autoplot

Multi-peak 2D Gaussian fitting in Autoplot

In any Heat Map figure (Layers → Run Analysis → 2D Density Fit or 2D Gaussian Surface Fit, Plus — free for 30 days), Autoplot fits 2 to 6 overlapping rotated 2D Gaussians locally on Apple silicon:

  • Automatic multi-peak mixture: set Peaks to 2–6 under Fit; Autoplot computes separated cKDTree initial seeds, solves bounded Trust Region Reflective least squares (maxfev = 60,000), and lists Peak 1 through Peak K sorted by amplitude alongside shared off ± err and R² in Results.
  • Multi-peak contours & centroids: enable Center marker (+ rotated crosses at every peak), Show fitted surface, and Contours using Sigma (1σ,2σ,...), explicit Fraction of Peak comma lists (recommended when peak amplitudes differ), or Z Value levels computed by Matplotlib (gaussian2d_mixture_contours).
  • ROI & reusable exports: turn on Use ROI (xmin, xmax, ymin, ymax) to isolate local clusters post-binning, then export Derived Functions (Export Fit Function), full-domain grids (Export Fit Surface), or sample-point evaluations (Save Z at Samples). For parameter sharing across peaks or K>6 without ROI splitting, run a custom Python script in the AI Assistant without sending raw numerical arrays off your Mac.

See features and pricing.

Frequently asked questions

Frequently asked questions
Why do my 1σ contour rings only circle the brightest peak in a multi-peak heat map?In 2D Gaussian (Multi-Peak) overlays, both Sigma (1σ,2σ,...) and Fraction of Peak scale contour z-levels from the single highest fitted component amplitude Amax plus offset, not independently per peak. Weaker peaks whose amplitude falls below 0.6065 * A_max will not intersect a 1σ ring—raise σ levels to 3 or 4, switch Levels to Fraction of Peak with lower fractions (e.g., 0.15, 0.30, 0.55), or enter explicit Z Value thresholds and turn on Center marker.
Why did σx and σy swap with a different rotation angle θ for one of my peaks?A rotated 2D Gaussian is symmetric modulo π/2: exchanging σx and σy while shifting θ by ±π/2 describes the exact same ellipse in the (x,y) plane. Inspect the rendered ellipse axes and Center marker orientation on the heat map rather than assuming σx is always the major axis.
How can I fit more than 6 Gaussian peaks in a single heat map?Autoplot's built-in Peaks stepper caps at 6 components (37 parameters) to avoid poorly conditioned Jacobians on binned grids. To decompose more than 6 peaks, build one source Joint Density Map or scalar heat map first, enable Use ROI under Range on separate fit layers to fit local clusters of 2–6 peaks, or use Custom Density Fit / Custom Surface Fit with an explicit sum-of-Gaussians formula and initial guesses.
When should I use unbinned scikit-learn GaussianMixture instead of Autoplot 2D Density Fit?Use unbinned Expectation–Maximization (GaussianMixture) when you have raw (X, Y) event coordinates with zero background floor (offset = 0), want normalized probability weights (∑πk=1), or want to avoid any grid-binning broadening on tiny sample sizes (N < 200). Use 2D Density Fit or 2D Gaussian Surface Fit when fitting empirical scalar-field surfaces z(x, y), separating peaks on a non-zero background offset, or exporting fitted surfaces and contour plots directly inside your figure workspace.

Sources

Algorithm details (fit_gaussian_2d_mixture, _gaussian_mixture_initial_centers, cKDTree 8-neighbor spacing radius clamped to [0.03, 0.18] diagonal, max(40, 25 * k) finite cell requirement, maxfev = 60,000 bounded Trust Region Reflective least squares, descending-amplitude component sorting, and gaussian2d_mixture_contours) and UI/rendering behavior (HeatMapFitCard, HeatMapFitCardRowView, HeatMapResultsPanel, and HeatMapChart peakScale = max_k A_k contour scaling) were verified directly against Autoplot source (math_logic.py, DataModel.swift, HeatMapGaussianMixture2DFitResult.swift, HeatMapFitCardRowView.swift, HeatMapResultsPanel.swift, HeatMapChart.swift, and docs/user-wiki/run-analysis/heat-density-gaussian-fit.md) and live renders from AutoPlot on 29 November 2026. Core spatial and optimization routines use SciPy `cKDTree` and `scipy.optimize.curve_fit`; unbinned mixture comparison references scikit-learn `GaussianMixture`. Trust Region Reflective bound-constrained optimization theory follows M. A. Branch, T. F. Coleman, and Y. Li, "A Subspace, Interior, and Conjugate Gradient Method for Large-Scale Bound-Constrained Minimization Problems," SIAM Journal on Scientific Computing 21(1), 1–23 (1999), DOI 10.1137/S1064827595289108; multi-Gaussian overlapping clump decomposition draws on J. Stutzki and R. Guesten, "High spatial resolution isotopic CO and CS observations of M17 SW - The clumpy structure of the molecular cloud core," The Astrophysical Journal 356, 513 (1990), DOI 10.1086/168859; and binned 2D Gaussian width/amplitude bias draws on M. K. Cheezum, W. F. Walker, and W. H. Guilford, "Quantitative Comparison of Algorithms for Tracking Single Fluorescent Particles," Biophysical Journal 81(4), 2378–2388 (2001), DOI 10.1016/S0006-3495(01)75884-5.

Try it on your own data.

Autoplot fits 2 to 6 overlapping rotated 2D Gaussians on Joint Density or Scalar Field heat maps with separated cKDTree seeding, Fraction of Peak contours, and center markers on Apple silicon. Part of Plus (free for 30 days).

Read 2D surface and joint density fitting →
Download .dmg

Without Private Cloud Compute · macOS 15–26

Apple silicon · macOS 15 or later · Free plan · Plus free for 30 days · 11 starter AI credits

Send to my Mac

Autoplot runs on a Mac. Send the link to yourself, or open it in the Mac App Store.