On this page
Why multi-peak 2D Gaussian fits collapse or swap labels
In an additive 2D mixture of rotated Gaussians over a single shared background offset, the model surface is:
where local rotated coordinates rotate by angle . Going from 1 to 6 peaks pushes the parameter count from 7 to 37, introducing three numerical failure modes absent in single-peak fits:
- 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. - Axis-permutation ambiguity ( vs ): whenever is unconstrained relative to major vs minor axes, rotating by and exchanging and yields the exact same ellipse—and as (nearly circular peaks), the standard error on diverges.
- 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.
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 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):
- Deduplication radius from 8-neighbor grid spacing: excess weight pairs with a
scipy.spatial.cKDTreeover finite binned cell centers . Eight-nearest-neighbor median spacing sets a local-maximum windowradiusclamped to[0.03, 0.18]of the domain diagonal and a minimum center separation0.5 * radius. - Separated local maxima before deterministic fallback: candidate centers are scanned in descending weight order, accepting local maxima inside
radiusthat satisfy the separation bound; if the surface is smooth and holds fewer than strict local maxima, a deterministic pass fills remaining seeds from well-separated high-weight cells. - Radius-clipped local moments per peak: instead of seeding widths from global variance across the whole map, each peak computes weighted moments inside a neighborhood capped at
min(0.18 * diag, 0.5 * min_other_distance)and initializes before running up to60,000bounded Trust Region Reflective evaluations, then sorts returned peaks (Peak 1,Peak 2, …) by descending amplitude .
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 .
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
Sigmacontours miss weak peaks: bothSigma (1σ,2σ,...)andFraction of Peakcompute contour -levels relative to the single tallest component ( and ). A secondary peak with never even reaches a1σcontour at ! SwitchLevelstoFraction of Peakwith explicit low fractions (such as0.16, 0.34, 0.56, 0.78), raiseσ levels(1…3or1…4), or enter exact physicalZ Valuethresholds alongsideCenter markercrosses. - Splitting dense fields (
K > 6) withUse ROI: built-in mixture fitting caps atPeaks = 6(37free parameters) to stay well-conditioned on gridded arrays. If your heat map contains8or12hotspots, build the source map once, toggleUse ROI(xmin,xmax,ymin,ymax) inRangeto fit subsets of2–6nearby 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 themax(40, 25 * Peaks)finite-cell minimum inside tight ROI boxes. KeepDensitynormalization 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:
| Workflow | Data representation | Max peaks & seeding | Parameter units & strengths |
|---|---|---|---|
Autoplot 2D Density Fit / Surface Fit | Binned finite grid cells (Density or Scalar Field) | 2–6 auto cKDTree peaks (ROI for larger clusters) | Unnormalized amplitudes , shared offset, ± stderr, interactive contours |
OriginPro (nlfit2d / Peak Analyzer 2D) | Matrix / XYZ worksheet | Replicable Gauss2D replicas; manual or grid guesses | Shared parameter bounds, weights, Windows batch worksheets |
SciPy curve_fit (custom script) | User grid arrays | Arbitrary ; user supplies and bounds | Full control over parameter tying (), residual weights |
scikit-learn GaussianMixture (EM) | Unbinned raw points | Arbitrary ; k-means++ initialization | Probability weights and full covariance ; no grid bias, no offset |
Use scikit-learn GaussianMixture when clustering unbinned 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.
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
Peaksto2–6underFit; Autoplot computes separatedcKDTreeinitial seeds, solves bounded Trust Region Reflective least squares (maxfev = 60,000), and listsPeak 1throughPeak Ksorted by amplitude alongside sharedoff ± errandR²inResults. - Multi-peak contours & centroids: enable
Center marker(+rotated crosses at every peak),Show fitted surface, andContoursusingSigma (1σ,2σ,...), explicitFraction of Peakcomma lists (recommended when peak amplitudes differ), orZ Valuelevels computed by Matplotlib (gaussian2d_mixture_contours). - ROI & reusable exports: turn on
Use ROI(xmin,xmax,ymin,ymax) to isolate local clusters post-binning, then exportDerived Functions(Export Fit Function), full-domain grids (Export Fit Surface), or sample-point evaluations (Save Z at Samples). For parameter sharing across peaks or without ROI splitting, run a custom Python script in the AI Assistant without sending raw numerical arrays off your Mac.
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 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 : exchanging and while shifting by describes the exact same ellipse in the plane. Inspect the rendered ellipse axes and Center marker orientation on the heat map rather than assuming 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 (), 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.