gratia (development version)
User visible changes
Plot aesthetic arguments for colours, opacity and line widths are deprecated in favour of ggplot2 component themes (#215). Existing default appearances are unchanged, and explicitly supplied arguments remain fixed overrides during migration. Apply
theme()with&to every panel in a patchwork, or with+to a single plot. For example, replacesmooth_colwithgeom.gratia.smooth = element_geom(colour = ...)andci_alphawithgratia.alpha.intervalinsidetheme(). Seegratia_theme_get()and the Customizing plots article for migration examples. gratia now requires ggplot2 >= 4.0.3 and patchwork >= 1.3.2.Native
mgcv::scasm()smooth estimation, drawing andconfint()now default tooverall_uncertainty = FALSE. An explicit request for unavailable overall mean uncertainty warns once (#372, #373).Breaking change: Sampling functions now use
n_drawsfor the total retained draw count andn_gridfor automatically constructed evaluation grids. Sampling controls must be named. Obsolete names, includingn,n_sim,n_vals,freq,newdata, andncores, produce migration errors.derivative_samples()takesmodelrather thanobject;add_*()sampling helpers takedatarather thanobject. Coefficient and*_samples()functions require an explicitn_drawswhen generating draws; supplied coefficient draws determine their own count and chains. Likelihood, LOO, WAIC and bayesplot wrappers usen_drawswith their documented defaults. Derivative sampling now defaults to a grid resolution of 200, matching smooth sampling; supplyn_grid = 100for the previous derivative resolution. Gaussian threads usen_threads, whilen_coreslimits concurrent MH chains. Explicit controls that do not apply to the selected sampler are rejected. Seevignette("sampling-migration").fitted_samples()rejects response-scale requests for general families without an expected-response adapter. Usescale = "linear_predictor"for the first predictor. Supported LSS families use their full expected response instead of treating location as the mean.Gaussian coefficient sampling for
mgcv::scasm()fits with linear inequality constraints now warns that the draws need not satisfy the fitted shapes. Metropolis-Hastings sampling now gives an explicit error because its proposals and likelihood calculation do not enforce those constraints.gratia has a new neon hex logo. The pkgdown site uses the pink g from the logo as its favicon.
Breaking change: Parametric plots now use the covariates as evaluated in the model by default:
log(x)is plotted againstlog(x), with a matching axis label. Useback_transform = TRUEto plot against the original covariates. This option is available indraw.gam(),assemble.gam(),draw.parametric_effects()anddraw.smooth_estimates(), including interaction axes, tensor products, rugs and conditioning facets (#412). Multi-column basis expansions retain their original covariate axes. Changing the coordinate scale does not change estimated effects or their intervals.The
transformargument ofparametric_effects()is deprecated. Replace it withback_transform = !transform(#412).Breaking change:
draw.gam()andassemble.gam()now default toparametric = NULL, including parametric terms alongside smooths whenselect = NULL. Selecting smooths explicitly continues to draw only those smooths, unlessparametric = TRUEis supplied. Useparametric = FALSEto restore the previous default. Additional panels can change plot layouts and the length of plot lists returned byassemble()ordraw(wrap = FALSE).Parametric effect intervals now include intercept uncertainty by default, including covariance between the intercept and the term. Partial estimates are unchanged. Use
overall_uncertainty = FALSEinparametric_effects(),draw()orassemble()to recover term-only intervals. Each term uses the intercept of its own linear predictor; models without an intercept are unaffected.Surface plotting and related evaluation functions now accept
n_2d, with a default of 50 points along each surface axis (#153). Default surface grids therefore shrink from 10,000 to 2,500 points per panel. Curve and conditioning slice resolutions can be controlled separately.Derivative functions now choose the finite-difference step automatically when
eps = NULL, using the fitted covariate range, derivative order and difference method. This reduces rounding error in second derivatives. Supply a positiveepsto specify an absolute step size.appraise()now automatically uses scalable plots when at least 10,000 observations were used for fitting. Setscalable = TRUEorFALSEto override this behaviour, or changescalable_threshold.Explicit
xlab = NULLandylab = NULLnow request default axis labels for continuous-covariatefsplots and random-effect tensor curves, consistent with other univariate smooths. Previously, explicitNULLsuppressed these labels (#308).Tweedie cumulative distribution functions now use fast Poisson-Gamma mixtures for
1 < p < 2instead of requiring the tweedie package (#410). The Gamma case (p = 2) uses native R distribution functions. Mixture calculations warn and return available approximations when their work or accuracy limits are reached. The tweedie package is now optional, in Suggests, and is needed only for numerical inversion requested withfallback = TRUE.posterior_samples()now uses separate random-number streams for coefficient and response draws. Response draws for a given seed differ from earlier releases, but remain reproducible.gratia now requires mgcv >= 1.9-4 and R >= 4.4.0.
glmmTMB support now requires the released version 1.1.15.2 or later, so the development version of glmmTMB is no longer needed.
New features
fitted_moments()andconditional_moments()estimate response means, variances, SDs, coefficients of variation, skewness and kurtosis. Delta-method intervals and joint Gaussian simulation propagate covariance between distribution parameters. Supported ML/REML fits also propagate estimated global family parameters and dispersion;nuisance = "fixed"explicitly conditions on their fitted values. Dispersion and coefficient covariance use the same ML/REML scale estimate as the saved fitting curvature, including models with linked or fixed smoothing parameters. Standard, distributional, categorical, multivariate-normal, grouped and latent censored response families are supported where their moments exist. Conditional moments can be drawn withdraw().smooth_estimates(),derivatives(), anddifference_smooths()offer continuous-interval Gaussian simultaneous bands for supported one-dimensional cubic splines viasimultaneous_method = "tube". Bands use a conservative threshold-crossing bound, preserve the selected covariance and group means, and record the domain and numerical diagnostics in interval metadata.draw(),assemble(), andconfint()forward the controls.Smooth estimation and drawing, including
difference_smooths(), now acceptvariablesto choose x and y axes and the order of conditioning facets. Differences between 3D and 4D smooths can now be drawn as faceted surfaces (#256, #257). Their automatic grids usen_3d = 16andn_4d = 4, matching individual smooths; useNULLto usenfor those dimensions. Resolved covariate orders are retained when drawing saved estimates. Supplydatato choose explicit conditioning values.Surrogate residuals are available for
mgcv::ocat()andmgcv::multinom()GAMs throughsurrogate_residuals(),type = "surrogate"in ordinary and scalable residual diagnostic plots, andadd_residuals(). Ordinal residuals follow Liu and Zhang (2018), with logistic references (#359). Nominal residuals follow Cheng, Wang and Zhang (2021), retaining a centred Gumbel utility component for every category, including category 0. All appraisal panels share one draw, and categories have separate panels. Both methods require no additional package and preserve accuracy in extreme tails.derivatives(),partial_derivatives(),smooth_samples()anddifference_smooths()now use workers configured bymirai::daemons()for independent smooth or comparison calculations (#348). Serial execution remains available without workers. Joint posterior draws, seeded simulation results and result order are preserved across worker counts. Custom smooth prediction methods are evaluated in the caller so workers use the same bases.Plots now support native ggplot2 theme settings for smooths, intervals, residuals, diagnostics and other components, including completed patchwork figures.
gratia_theme_get(),gratia_theme_set()andgratia_theme_update()manage the optionalgratia.plot.themeoverride.gratia_palette()provides optional Paul Tol palettes. Current default appearances are retained, including group legends without symbols for fixed-colour partial residuals (#215).All 43 smooth constructors in scam 1.2-23 are supported for smooth estimates, bases, sampling and plots, including bivariate smooths, cyclic margins, interactions and explicit
Byclasses. This includestediandteidsurfaces that increase along one covariate and decrease along the other.draw()andassemble()acceptcentre = "plot"to match scam’s centring of bivariate displays; the default retains the fitted function. SCAMsmooth_type()labels use compact descriptions such asP spline (inc)andTensor (inc, free). Saved estimates with earlier type labels remain drawable. Plot captions describe the basis and constraints separately, using arrows for monotonicity, covariate names for tensor constraints and fitted change points for local constraints. Saved smooth estimates retain these captions.SCAM models gain conditional simultaneous smooth bands, derivatives, contrasts, conditional predictions, parametric effects, residual helpers, model summaries, concurvity, penalties and variance-component ratios. Independent-response likelihoods, LOO/WAIC, supplied coefficient draws and scalable posterior predictive plots are also supported. Concurvity excludes basis columns whose coefficients are fixed to zero, restoring the correct calculation for curves that become flat. See the SCAM support article for supported combinations and uncertainty calculations.
shape_intervals()applies monotone rearrangement and convex or concave envelopes to existing interval endpoints on a finite grid. Supported scasm smooths expose this throughinterval_method = "shape"and an explicit Gaussian or stored-bootstrap initial source. The transformation preserves whole-grid containment events; it does not establish nominal coverage or preserve marginal coverage of pointwise limits.shape_confidence_set()andin_shape_set()represent and inspect intersections with coefficient inequalities and equalities. See the shape-constrained intervals article for supported combinations, tensor requirements and examples (#372, #373).draw()andassemble()also acceptfrequentistfor the initial smooth covariance calculation. Generalpcreplacements and derivative bases are rejected when they do not justify the named function shape. Curvature requires equally spaced fitted knots to rounding precision, and extrapolation is rejected. Convex envelope interpolation preserves exactly flat segments. Saved estimates reject interval computation controls that require the fitted model.interval_methodselects native scasm bootstrap or Gaussian pointwise intervals for smooths, fitted values, smooth derivatives andconfint(). Shifting or transforming smooth confidence intervals retains asymmetric limits. Replacing saved intervals withadd_confint()records their Gaussian source. Automatic selection uses stored bootstrap draws, including mgcv’s smoothing-bias correction. Simultaneous bootstrap bands remain unsupported (#372, #373).Scasm captions show retained shape constraints with portable mathematical arrows. Saved estimates retain constraint metadata for each tensor margin; ignored requests are labelled and produce a warning (#373). This includes named requests replaced by general
pcinequalities. Shape-enforced intervals keep the basis and constraint caption without adding interval details; those remain in the documentation and metadata.Gaussian simultaneous bands now support positive-semidefinite coefficient covariance matrices, including scasm fits with exact equality constraints.
penalty()extracts stored tensor andt2()penalty matrices, including marginal penalties viamargins = TRUEand their original scaling.Posterior sampling supports multiple chains, including parallel MH chains using mirai. Workers started for sampling exit cleanly so coverage data can be written completely.
n_draws = 1000, chains = 4retains 250 draws per chain after separate burn-in. Chain identities are preserved through fitted, response, smooth, and derivative samples.as_mcmc_draws()converts draws for posterior, coda, and bayesplot;diagnostics = TRUEandsampling_diagnostics()provide coefficient convergence summaries and acceptance rates (#281).draw(sampling_diagnostics(x))plots native coefficient traces or pooled-rank histogram outlines by chain. Sampling withdiagnostics = TRUEretains the coefficient draws for these plots through fitted, response, smooth and derivative sampling. LSS sampling supports fitting rows, subsets and new covariates without observed responses. All distribution parameters use the same coefficient draw. Fitted response samples and their derivatives evaluate the expected response, including means that depend on scale, shape or hurdle probabilities. Fixed-coefficient response sampling uses the same parameter transformations. Missing predictors or explicit sampling weights produceNAresponse draws consistently. LSS response generation now reuses model-matrix blocks and constructs the output table once, preserving seeded responses and chain identities.mh_backend = "gratia"adds a compiled MH evaluator for common response families in ordinary gam and bam fits with independent observations. Large designs can be evaluated in blocks.mh_backend = "family"uses the compiled MH loop with the fitted family’s likelihood functions, including compatible extended, grouped, and multiple-predictor families. It prepares and reuses a full design matrix, smoothing penalty, and proposal factorisation across chains. Smoothing parameters and parameters outside the coefficient vector remain fixed; LSS scale and shape coefficients vary jointly with location. The default backend remainsmgcv::gam.mh(). The new backends reject BAM fits with nonzero prescribed smooth contributions, where native fitting and prediction use different offsets.data_sim()accepts descriptive aliases for the original example models, including"additive","bivariate_surface","gu_wahba_f2"and"luo_wahba_f6". All existing names remain supported and produce identical seeded output.ale()computes accumulated local effects for numeric covariates inmgcv::gam()andmgcv::bam()fits, with link and response scales, distribution parameters, and pointwise or simultaneous intervals.draw()plots saved results with parameter labels and a scale caption. Prediction blocks can use workers configured bymirai::daemons(). Block accumulation order, shared interval draws and caller RNG handling are preserved. Custom prediction methods and transformations that require caller functions or S3 methods retain serial prediction. Method checks do not invoke active or lazy caller bindings.data_sim()now accepts family objects, explicit predictors and generating parameters for scalar, location-scale, categorical, multivariate and Cox models. Censored families can return observed intervals while retaining complete responses and true distribution parameters. Grouped families can use repeated distributions with separate parameters.data_sim()gains analytic shape reference functions and fitting recipes formgcv::scasm(), including combined shape constraints, tensor surfaces and Gamma models with constraints on the log mean and log dispersion. The additive Poisson recipe uses 240 observations andk = 6for each smooth to avoid fitting errors with mgcv 1.9-4.residuals_covariate_plot()andscalable_residuals_covariate_plot()plot complete-model residuals against numeric or categorical covariates and pairs of numeric covariates. Exact mgcv smooth labels can select their constituent covariates. Grouped displays, mean trends and joint maps help identify remaining mean structure or changes in residual spread. By default, mean trends are fitted only for groups with at most 20,000 observations;smooth = TRUEorFALSEoverrides this limit.Optional
bayesplot::pp_check()methods provide posterior predictive checks for supported GAMs and mixed models (#278, reported by @nicholasjclark). Sampling controls, including chains, are supplied throughsampling_args. Response draws remain aligned with likelihood draws for leave-one-out plots, including supplied matrices with stored chain and draw identities.log_lik()and optionalloo::loo()andloo::waic()methods support approximate predictive comparisons for independent GAM/BAM fits (#278, reported by @nicholasjclark). They retain coefficient diagnostics and chain identities. LOO uses stored iteration order for relative effective sample sizes without changing the likelihood draw order; unlabelled supplied draws need explicit efficiency or chain information.Diagnostic plots now support native inlaws families through their supplied
gratia_diagnosticsfunctions, including grouped-family fits and models with multiple response columns.dharma_residuals()andtype = "dharma"in diagnostics now calculate simulation-based PIT residuals using gratia’s response generators, without requiring DHARMa or mgcViz.n_dharmacontrols the simulation count. Residuals retain zero and one endpoints and are shared acrossappraise()panels. QQ and worm plots use uniform references with approximate pointwise bands for independent responses; dependent responses omit these bands.mgcv-compatible families can now supply a
gratia_diagnosticsfunction for response means, variances, probability bounds and distribution functions. This allows diagnostics for additional count, ordinal, mixture and censored families without adding family-name checks to gratia. Traditional simulated reference residuals can apply a supplied observation process. See?family_diagnosticsfor the interface.New site articles explain model diagnostics, grouped surveys, glmmTMB and sdmTMB models, prediction comparisons, response distributions, and smooth effects on different spatial domains. They include fitted examples and explain the assumptions behind estimates, intervals and checks.
Residual diagnostics and posterior predictive checks now cover
lm,glm,gam/bam,gamm/gamm4, glmmTMB, univariate GJRM and sdmTMB models using their fitted response distributions. Probability integral transform (PIT) residuals map observations to fitted probabilities, randomising over probability mass for discrete responses. Quantile residuals convert those probabilities to standard-normal scores. See?diagnostic_supportfor supported families, conditioning choices and limitations. Prepared diagnostic objects carry the selected conditioning and sdmTMB field choices through residual and plotting methods.Mixed-model diagnostics can hold fitted random effects fixed or average over their fitted distribution. Joint response simulations use the fitting packages’ generators to retain temporal and spatial covariance and shared random effects. Marginal residuals can use means, variances and ranks from these simulations. Direct
nlme::lme()andlme4::merModfits also support residual and posterior predictive checks. Non-Gaussiangammfits estimated by penalized quasi-likelihood (PQL) support approximate checks when they have no residual working correlation. nlme calculations retain covariance between random effects in block designs, fitted factor contrasts and observation order after subsetting or missing-value removal.sdmTMB residual diagnostics now offer four ways to treat random fields: draw fitted fields once from their approximate posterior and hold them fixed (
field_method = "mle-mvn", the default), hold field estimates fixed (field_method = "mle-eb"), average over fitted-field uncertainty (field_method = "mle-mvn-integrated"), or simulate new fields (conditioning = "marginal"). Plot labels identify the choice. Posterior predictive checks separately include approximate parameter uncertainty. See?diagnostic_supportfor what these checks assess and their limitations. Delta-model diagnostics use the response family’s dispersion parameter. Fits with a dispersion formula give an explicit error because observation-specific dispersion is not yet supported by these diagnostics.Diagnostic plots now support uncensored univariate
GJRM::gamlss()models with N, LN, GA, GAi, P, NBI and NBII families. They use randomised quantile residuals with a standard-normal reference. Observed-versus-fitted panels show response means calculated from the final distribution parameters. NBII probabilities are calculated from the final fitted likelihood parameters, rather than relying on stored probabilities that can use a Poisson distribution.appraise(),qq_plot()andworm_plot()now support native glmmTMB residuals, with conditional response simulation for QQ reference bands. See?'glmmTMB-methods'for supported families and current limitations. Gaussian predictive draws use glmmTMB’s standard-deviation parameterisation. Variances for truncated count distributions are calculated accurately even with tiny means.Grouped-family diagnostics now support quantile residuals with appropriate standard-normal references and consistent component colours. Traditional residuals use separate facets for each component (#267). Pooled histograms use pale fills and solid step outlines in each component’s colour, so overlapping distributions remain visible. Ordinary and scalable plots use the same bin edges and calculate each component’s density separately.
Distribution checks now cover more mgcv families, including
shash(),twlss(), ordinal,ziP()and grouped families. The internalfix_family_qf()extends mgcv’sfix.family.qf()with experimental support forscat(),tw(),Tweedie(),gaulss(),gevlss(),gumbls(),gammals(),ziplss()andmvn().fix_family_cdf()adds cumulative distribution functions forgaulss(),gevlss(),gumbls(),gammals(),ziplss()andmvn(), making quantile residuals available. Formvn(), both helpers use each response’s marginal Gaussian distribution with its fitted variance (#183). Categorical CDFs and quantiles formultinom()use mgcv’s category codes0, ..., Kas the accumulation order, enabling randomised PIT/quantile residuals and inverse-CDF diagnostic references (#183). These helpers andfix_family_rd()preserve distribution functions supplied by callers.ziplss()quantile residuals randomise over the probability mass of each observed count (GRA-007). Quantile helpers retain log probabilities where supported; conversions that cannot represent an extreme probability give an explanatory error rather than a false infinite quantile.New Tweedie quantile helpers support uniform QQ diagnostics (#410). They use fast Poisson-Gamma mixtures for
1 < p < 2and native R distribution functions for the Gamma case (p = 2). Expensive numerical inversion is available withfallback = TRUEand the optional tweedie package. Mixture calculations warn and return available approximations when their work or accuracy limits are reached. Withmethod = NULL,appraise(),qq_plot()andworm_plot()automatically select simulation fortw()andTweedie()models, avoiding numerical quantiles. Other ordinary GAM families prefer"uniform", with fallbacks when a method is unavailable. An explicit method overrides the automatic choice.quantile_residuals()now supports censoredcnorm(),cpois()andclog()models, randomising over censoring intervals for PIT and quantile residuals. These families also gain cumulative distribution and quantile helpers, andfix_family_rd()provides random generation for their latent, uncensored responses. Thecnorm()andclog()generators use the fitted family scale and prior weights. Tail probabilities are calculated on the logarithmic scale where supported to avoid numerical infinities.Inverse Gaussian distribution functions now support PIT/quantile residuals and inverse-CDF QQ/worm plots without additional dependencies. Their calculations account for prior weights.
Explicit GAM sampling weights override response precision or binomial trial counts.
posterior_predictive_plot()compares observed responses with posterior predictive distributions, using density curves for continuous responses and points with interval bars for discrete responses. Setappraise(ppcheck = TRUE)to replace the residual histogram with this check. Plots summarise all draws on a shared grid; discrete responses with more than 512 distinct values use labelled probabilities for 512 bins.Five new
scalable_*_plot()functions provide binned QQ/worm plots, residual-density heatmaps, histograms and observed-versus-fitted heatmaps. They use all observations while keeping plotting data compact. Residual heatmaps estimate the density at each predictor value withKernSmooth::bkde2D()by default. A square-root colour scale makes low-density regions easier to see. Usedensity_method = "histogram"for unsmoothed bins, orbandwidthto control smoothing on both axes. Heatmaps of counts remain unsmoothed. Plot objects store the grid rather than all observations. KernSmooth is an imported dependency.QQ reference calculations now average draws as they are generated, or use temporary files for exact simulated quantiles above the configured memory limit. This reduces memory use without discarding reference draws. Simulated GAM QQ and worm plots are also faster, with unchanged numerical results.
residual_correlation()andresidual_correlation_plot()provide approximate checks of serial structure, including for BAM models that apply AR1 to working residuals. They omit significance bands based on independence.draw(),smooth_estimates()and smooth coefficient extraction now support glmmTMB models, including conditional, zero-inflation and dispersion smooths where glmmTMB supports them. All smooths are plotted by default, with mgcv-style predictor labels (s(x),s.1(x), etc.) andselectapplying across the model. Parametric effects and native random effects are also plotted, including for models without smooths. Native random intercepts and slopes use separate Gaussian QQ panels. Setranef_lines = TRUEto replace a simple(1 + x | g)pair with lines showing its random contribution only; more complex terms retain QQ panels. Effect intervals use TMB joint covariance. See?'glmmTMB-methods'for current limitations.draw()andassemble()now support formula smooths and parametric effects from sdmTMB models, including both predictors of delta models. Companion methods provide smooth labels, coefficients and effect estimates. Support requires sdmTMB >= 1.2.0 models fitted with the RTMB backend. Smooths use joint RTMB covariance; tensor smooths with multiple penalties are supported.Smooth plot subtitles now identify the model part or distributional parameter for glmmTMB, mgcv and
GJRM::gamlss()models with multiple linear predictors. Single-predictor models omit these labels, and constant glmmTMB dispersion alone does not trigger them. Information aboutbyvariables, smooth titles, selection and the default of plotting all smooths are retained. Savedsmooth_estimates()retain the labels in an optional.modelcolumn.Soap-film boundary (
bs = "sf") and wiggly (bs = "sw") components are now supported, with distinct component types and boundary-aware plots (#375).Grouped-family models fitted with
mgcv::gfam()now support response-scalefitted_samples()with component-specific mean transforms (#269), andsimulate()with component-specific distributions and parameters (#272). These functions andposterior_samples()accept supplied data andfamily_indexfor component membership without observed responses. Posterior responses preserve joint coefficient draws, component labels, offsets and sampling weights; ordinal response-scale fitted draws remain unsupported. Derivative sampling retains family membership when shifting supplied covariates.Support for classed gamm4 models now covers smooths, parametric effects, predictions, derivatives, simulations, posterior draws and variance components. Smooth and prediction methods describe the population GAM component and exclude additional terms supplied through
random. Models require gamm4 >= 0.2-7; historical unclassed lists are unsupported. See?gamm4_supportfor covariance and sampling limitations, and for the full-model conditioning options used by diagnostics and response draws. Diagnostics, response simulations and posterior predictive checks use the full fitted mixed model withconditioning = "conditional"by default. Response references hold fitted smooth and grouping effects fixed; posterior predictive checks include uncertainty in those fitted effects. Selectconditioning = "gam_component"to use only the extracted GAM component. This choice is required when supplying coefficient draws or prediction data toposterior_samples(); full-model draws use fitting observations only.parametric_effects()anddraw()now support parametric interactions, including higher-order interactions. Numeric interactions use surfaces and conditioning facets; numeric-by-factor interactions use grouped curves; factor interactions use grouped estimates and intervals. Interaction surfaces centre the default diverging palette at zero, using a common fill range across facets; fixed scales expand the fill range as for smooth surfaces (#411).Smooth evaluation, plotting, bases, sampling and prediction now support functions of covariates such as
s(log(x)), including transformed offsets and anenvirargument for local functions and constants. Stored evaluated covariates allow smooth plotting when the original data or functions are unavailable. Automatic smooth grids retain transformed coordinates, andderivatives()andpartial_derivatives()can differentiate with respect to raw covariates usingwrt = "covariate". Seevignette("transformed-covariates", package = "gratia")for examples. Evaluation failures at new data produce actionable errors. Parametric effects and data slices recover raw covariates consistently.simulate()andadd_fitted()also acceptenvirfor local functions in offsets and smooth expressions.smooth_estimates(..., back_transform = TRUE)now recovers raw fitting covariates, generates grids on their original scale and evaluates model expressions on those grids (#412). This supports custom functions such asfoo(x)and tensor products without needing inverse functions. Smooth grids retain their existing model-scale defaults. Drawing precomputed estimates on the original scale requires retained raw coordinates; estimates with only transformed coordinates give an informative error. Parametric effects retain both scales by row, including for many-to-one transformations. Coordinate columns survive confidence-interval calculation and subsetting. Typical values of other covariates are not treated as raw axes, and numericbymultipliers can share a raw axis name. Drawing usesenvirto recover observations. Supplied prediction data remain usable when raw observations for rugs or residuals are unavailable. Transformed soap-film boundaries cannot be drawn on the original scale and give an explicit error. Irregularly spaced surfaces use rectangles to preserve covariate positions (#412).Full and reduced-rank Markov random field (MRF) smooths now support area effect estimates and interval plots (#9). Use
mrf_plot = "qq"for a descriptive QQ plot.draw(),assemble()andsmooth_estimates()now support simultaneous bands for individual smooths (#314).interval = "credible"is an alias for pointwise"confidence"intervals.Numeric smooth and parametric surfaces can now be drawn in 3D with
surface = "3d", using the optional ggcube package (#393). The existing RdBu fill palette, theme, conditioning facets, contours and masking are retained.surface_3d = list(...)controls the view without applying ggcube’s theme. Lighting defaults tobackface_scale = 1; supply a customlightthroughsurface_3dto override it. Opaque faces, contours and floor observations share depth ordering so hidden features are occluded. Setci_3d = TRUEto add translucent lower and upper interval surfaces to smooths and numeric parametric interactions across supported model classes.ci_3d_alphaandci_3d_colstyle the bounds independently of curve ribbons. Interval surfaces retain the estimate’s mesh and masking; their heights expand the vertical range without training the continuous fill scale.draw()andassemble()now acceptsurface = "tile"to draw flat smooth surfaces with vector rectangles; the default remainssurface = "raster"(#308). Bivariate, trivariate, quadvariate, tensor-product and soap-film surfaces use the same rendering options.Random-effect tensor-product plots now accept
re_levelsto select factor levels.n_3dandn_4dalso limit the number of factor levels used for conditioning facets (#169).draw()for penalty matrices now acceptsgeom = "tile"to draw individual rectangles;geom = "raster"remains the default (#392).response_derivatives()now supports delta-method standard errors and pointwise intervals viauncertainty = "delta". Both uncertainty methods return.se; posterior simulation remains the default.conditional_differences()compares conditional fitted values between factor levels or joint factor combinations on the link or response scale, with pointwise or simultaneous intervals using the delta method or shared posterior simulations. Simultaneous bands can cover each comparison separately or all comparisons jointly viasimultaneous_scope.draw()plots the differences and their intervals (#143, #145).difference_smooths()now offers simultaneous intervals for differences of smooths at supplied covariate combinations, separately for each pair of factor levels, viainterval = "simultaneous"(#380). Pointwise intervals remain the default.fitted_values()now offers simultaneous intervals for fitted values at supplied covariate combinations viainterval = "simultaneous"(#4). Pointwise intervals remain the default. Simulation size, parallel sampling and seeds can be controlled, as inderivatives()andpartial_derivatives(). The legacyfderiv()implementation is unchanged.fitted_values()now emits a message identifying prediction rows with unobserved combinations of known categorical predictor levels (#164).all_levels()is now an alias ofevenly()with a name intended for factors (#217).data_slice()gains a.byargument to evaluate slice expressions within observed groups. For example,x = evenly(x)can use a separate range for each factor level, which is useful for models with factorbysmooths (#196).conditional_values()now acceptscomplete = FALSEto retain only observed combinations of factor conditions while preserving numeric prediction grids (#337).confint.gam()andsmooth_estimates()now acceptfrequentist = TRUEto use the frequentist covariance matrix. The default remainsFALSE. Simultaneous intervals use the selected covariance matrix consistently (GRA-005).get_vcov()is now exported for extracting a model’s covariance matrix.gratia now supports the
clognorm()family from mgcvUtils.link(),inv_link()and other family utilities now supportcpois(),clog()andbcg(). These families also work withfitted_values(). Single-link families can use their supplied link functions without needing a recognised family name.
Bug fixes
partial_residuals()andadd_partial_residuals()now give an informative error for models without working residuals or working weights, including mgcv’s location-scale families.draw(residuals = TRUE)warns once and draws the smooths without partial residuals for these models (#414).draw.difference_smooth()now uses suppliedxlabandcaptionvalues when drawing differences between curves.n_smooths()now counts smooth terms in glmmTMB models across the conditional, zero-inflation and dispersion predictors, excluding native random effects. Models without smooths return zero (#240).Direct calls to
smooth_estimates()now work forGJRM::gamlss()models (#352). Estimates use the final fitted coefficients and covariance, with smooth selection across equations and parameter labels retained for drawing saved estimates. Frequentist covariance also comes from the final fit; unavailable smoothing-parameter corrections warn and use its Bayesian covariance.B-spline evaluation handles empty data and factor-by calls whose evaluation data omit fitted levels, including constrained tensor products.
MH acceptance rates are extracted from the correct mgcv return components.
data_sim()now transforms theeg6predictor once and returns the predictor used for sampling. Grouped-family simulations respect seeds, parameters, ordinal aliases and repeated family positions;distis ignored throughout that legacy example. Theeg5andeg6examples accept sample sizes not divisible by four. Explicit seeds restore an absent RNG state, and reference generation forwards the requested Tweedie power. Vector Tweedie parameters now use the correct compound Poisson-Gamma law.Large QQ reference simulations now close their file connections before removing temporary files, allowing cleanup to complete on Windows.
SCAM smooth estimates and standard errors no longer depend on the other rows in the evaluation grid. Single-row and short-grid evaluations are supported.
overall_uncertainty = TRUEincludes intercept variance and its covariance with the smooth;FALSEincludes smooth uncertainty alone.unconditional = TRUEnow gives an explicit error because SCAM calculations do not support smoothing-parameter uncertainty. Smooth and full-model predictions now share coefficient mappings, including endpoint and local constraints. Formula transformations, offsets and missing training rows retain their fitted meaning. Themifosmooth is rendered.SCAM coefficient draws now sample unrestricted fitting parameters and apply the fitted positivity transformation, preserving the smooth constraints. Singular positive semidefinite covariance matrices are supported; invalid covariance matrices and non-finite transformed draws give explicit errors. Gaussian AR1 response simulation now uses fitted correlation and series boundaries instead of drawing independent responses.
Partial derivatives, fitted samples and smooth samples of soap-film smooths include the contribution from known boundary values. Complete-predictor derivative samples also differentiate those fixed values, without adding coefficient uncertainty. Term exclusions retain only the appropriate fixed contributions. Separate sampling per smooth now correctly subsets supplied coefficient draws.
Multinomial fitted samples now honour
scale = "linear_predictor", returning log odds relative to the reference category instead of probabilities. Both scales retain all category labels; the reference predictor is zero. Models with one non-reference category also use this output format.GJRM smooth selection now uses one order across all model equations. Character selections draw only the equations containing the selected smooths; repeated labels have distinct keys returned by
smooths().wrap = FALSEreturns a flat list of plots.Student-t sdmTMB models now support residual diagnostics and posterior predictive plots with fixed or estimated degrees of freedom. Pearson residuals require degrees of freedom above two. Quantile residuals and predictive checks remain available with infinite variance. Predictive plots also work for additional native sdmTMB families without requiring an analytic residual distribution.
Smooth plots drawn with
scales = "fixed"calculate their shared ranges from finite estimates and interval bounds. Missing soap-film boundary rows no longer cause each component to use a separate colour scale.Parametric interaction plots for glmmTMB and sdmTMB retain their term and coordinate information across model components. This prevents factor interactions from being mistaken for numeric effects when drawing rugs.
Response distributions now correctly account for Gaussian and Gamma dispersion with observation weights, factor-valued Bernoulli responses and numeric binomial trial counts.
Beta diagnostics now include the probability mass created by clipping native draws at epsilon endpoints. Binomial probabilities immediately below an observed value are calculated more accurately.
GEV and sinh-arcsinh residuals now use stable means and correct centering and signs. Undefined moments remain unavailable. Invalid sinh-arcsinh deviance contrasts give an explanatory error; PIT/quantile checks remain available.
Quantile residuals now calculate probabilities on the logarithmic scale in the smaller tail for families that support this calculation, including Poisson and negative binomial. This avoids numerical infinities without clipping probabilities.
Grouped-binomial quantile residuals now randomise over the probability mass of one success rather than one whole response proportion.
BAM models that apply AR1 to working residuals using a generalized estimating equations (GEE) approximation retain marginal PIT, quantile and QQ checks. QQ plots no longer switch automatically to normal references or use bands that assume independence. The working correlation does not specify a joint response distribution, so joint response simulation and posterior predictive checks are unavailable. Gaussian identity-link AR1 response simulation remains supported.
QQ bands for dependent responses now use joint simulations when available. Otherwise, the plot explains why the bands are omitted.
Fitted and posterior response draws, response simulations and diagnostics now retain offsets supplied as fitting arguments for fitting observations, including ordinary
bam()and extractedgamm4()GAM components. Recovery keeps formula offsets, prescribed smooth boundaries and additional group effects separate. Explicit prediction data still follow the fitter’s prediction convention and do not inherit argument-only fitting offsets.Explicit seeds now preserve the caller’s random-number state for coefficient and response draws.
worm_plot()also honoursseed, including throughappraise(use_worm = TRUE), and restores the caller’s random-number state after seeded calls (#407).For models fitted with
na.exclude, default fitted values, partial residuals, fitted and posterior samples, simulations andquantile_residuals()now restore excluded rows asNA. Diagnostics align retained observations with predictors, and histogram bin selection handles missing residuals (#349, #402). Explicit prediction data preserve row positions by default: missing required predictors yieldNA, while missing responses alone do not prevent prediction. Discretebam()fitted-value intervals restore exclusions once and accept stored fitting frames without relying on tibble subsetting in native prediction.link(),inv_link()andextract_link()now reject unsupported parameters consistently. Fortwlss(),scale,sigmaandphiselect the third linear predictor, andpowerselects the second. Explicitwhich_etaindices formvn()andmultinom()are now respected and validated.Custom smooth labels supplied through
draw(..., subtitle = ...)and other label arguments now reach the smooth renderer correctly.Parametric plot coordinates on the model scale now contain the evaluated predictor rather than its coefficient-weighted partial contribution (#412).
typical_values()anddata_combos()no longer require anenvirargument to recover model covariates.Automatic surface fill ranges now ignore non-finite estimates and standard errors (#308).
Random-effect tensor products now plot curves, categorical estimates and faceted surfaces consistently across
te(),ti()andt2()(#169). Two-factor products use points with confidence intervals, faceted by the second factor, rather than empty line plots. Products with one factor use the continuous covariate on the x axis regardless of margin order (#395). Three- and four-variablet2()smooths with factor margins produce faceted surfaces.Spline-on-the-sphere plots now use valid cells at the poles and date line, with orthographic clipping and separate factor-by panels (#277).
draw.gamlss()now sizes its plot layout using the panels actually drawn, including parametric effects, avoiding rendering errors for GJRM models.Posterior sampling for GAMs, including the GAM component of gamm4 models, now falls back to
mgcv::rmvn()with a warning if the default sampler’s Cholesky decomposition fails (#332).smooth_estimates()now uses the fitted coefficient order for random-effect interactions fitted withbam(discrete = TRUE), correcting estimates and standard errors (#387).assemble()anddraw()now honourtermswhen selecting parametric effects, while retaining the selected smooths (#368).variance_comp()now handles variance components without confidence intervals, including default GCV fits, and returns a typed empty table whenmgcv::gam.vcomp()returns no components (#377).rtw()now assigns Gamma shapes to the correct observations when Tweedie power varies, including intwlss()response simulation. Scalar parameters are expanded consistently, and incompatible lengths or non-finite inputs are rejected (#409).data_sim()now honours custom cut points for ordinal responses and validates that they are finite, strictly increasing and consistent with the requested integer number of categories (#408).draw.rootogram()now applies the square-root transformation when a custom y-axis label is supplied, keeping plotted frequencies independent of the label (#406).overview()now reports one degree of freedom per parametric coefficient, avoiding incorrect values and row-length errors for factors and models without an intercept (#405).Loading gratia no longer changes
weights()dispatch for linear models. QQ and worm plots preserve observation weights and excluded rows (#404).fixed_effects()now excludes smooth coefficients using their model indices, so tensor-product smooth coefficients no longer appear as parametric effects (#403).data_combos()now honourscomplete = FALSE, returning only observed combinations of factor levels while retaining typical continuous values and variable selection (#400).derivatives()andpartial_derivatives()now preserve the correct smooth selection when excluding random-effect or unsupported smooths, avoiding logical-index recycling warnings under R-devel.partial_derivatives()aligns focal variables and output labels with the selected multivariate smooths, including when univariate smooths are skipped (#396).derivatives.gam()now explains when requested smooths are unsupported, with a message if some cannot be handled or an error if none can. This covers multivariate smooths such ass(x1, x2),te(x1, x2),ti(x1, x2)andt2(x1, x2), as well as random-effect smooths (#389, reported by @mikeguggis in #362).compare_smooths()now honoursunconditional = TRUEwhen computing standard errors (#397).Adding a constant to parametric effects now shifts estimates and confidence intervals together, including when drawing or assembling plots (#398).
Gaussian rootograms now use response-scale means and standard deviations adjusted for prior weights when computing expected counts. Nonpositive or non-finite prior weights are rejected (#399).
fitted_values()now computes correctly ordered confidence bounds for location-scale-shape, zero-inflated Poisson (ziplss()) and Tweedie location-scale-shape (twlss()) models. Response-scale intervals retain ordered endpoints for decreasing inverse links, as do transformed intervals fromconfint.gam()(GRA-001).post_draws.default()andgenerate_draws.gam()no longer useseed = 0for every call withseed = NULL. They now generate a valid integer seed without modifying the caller’s random-number state (GRA-002).derivatives()now holds numericbyvariables fixed when computing derivatives of smooths. Previously, finite differences shifted both the smooth covariate and its numeric multiplier, giving incorrect derivatives, standard errors and intervals. Only the current smooth’s covariate is now shifted, for supplied data and automatically generated grids (GRA-003).difference_smooths()now matches smooth covariate combinations across factor levels before computing contrasts. Previously, different row orders in supplied data could silently compare different covariate locations, giving incorrect differences, standard errors and intervals. Duplicate combinations and mismatched grids now produce informative errors; comparisons at a single location also work (GRA-004).confint.gam()now uses consistent covariance and standard errors for simultaneous intervals, respectingunconditional. These intervals exclude overall-mean uncertainty, as documented (GRA-005). Requesting multiple smooths no longer causes an error (GRA-006).simulate.gamm()now respects the supplieddataargument.smooth_samples.gamm()andoverview.gamm()now forward additional arguments to their underlying GAM methods instead of ignoring them (GRA-008).
gratia 0.11.2
CRAN release: 2026-02-07
User visible changes
gratia now only handles shape constrained models fitted using scam version 1.2-21 or later. This is due to breaking changes in scam, and new functionality in that package, which simplifies gratia.
gratia also now depends on dplyr version 1.2.0 or later.
Histogram bars drawn by
residuals_hist_plot()and points inqq_plot(),residuals_linpred_plot(),observed_fitted_plot(), andworm_plot(), and henceappraise(), are now filled with a dark shade of grey and use a light colour for the border of the bars.
New features
-
derivatives()now works for constrained factor smooths (bs = "sz"), treating them in the same way as random factor smooths (bs = "fs"). Lack of support reported by @vrest-png #362Also handles higher order
bs = "sz"terms. draw.derivatives()can now differentiate random and constrained factor smooths through the colour aesthetic via new argumentdifferentiate_factor_smooths.model_terms()returns the names of all terms in a model. #388
Bug fixes
parametric_effects()now excludes interactions in models with multiple linear predictors, matching the existing single-predictor behaviour (#369).conditional_values()would fail if supplied a numeric vector of data to condition on via theconditionargument. #366gratia worked inconsistently with tensor product smooths containing a random effect
bs = "re"marginal. Reported #358 and fixed by @asgersvenning #360, with additional changes by Gavin Simpson.Argument
mvn_methodwas not being passed on to the lower workhorse functions that did the sampling. #381response_derivatives()would fail if there were no other terms in the model but the focal term.
gratia 0.11.1
CRAN release: 2025-08-25
User visible changes
-
residuals_hist_plot()and henceappraise()now centre the middle bin of the histogram at 0. In part this was due to ggplot2’s new binning algorithm leading to potentially odd choices for the bin breaks in the context of model residuals.
New features
-
quantile_residuals()now supports more of mgcv’s families: - Several user friendliness improvements in
partial_derivatives():- now better handles the case where there are multiple smooths for which partial derivatives are required,
- correctly identifies smooths that involve random effect terms (i.e. any smooth or tensor product marginal smooths with
bs %in% c("re", "fs")) and ignores them, - identifies and ignores univariate smooths, and
- displays more informative error messages to explain what was wrong.
Bug fixes
partial_derivatives()threw an error when theselectargument was used. #356 reported by @BenFN121draw.conditional_values()was setting a label on the fill aesthetic even if that aesthetic was not being used. In ggplot2 v4.0.0 this resulted in a warning, which is fixed.
gratia 0.11.0
CRAN release: 2025-08-18
gratia now has a paper describing the package in the Journal of Open Source Software. If you use gratia in your work, please cite this paper rather than the generic citation previously created by citation():
Simpson, G.L. (2024) gratia: An R package for exploring generalized additive models. The Journal of Open Source Software 9, 6962.
User visible changes
Experimental support for computing with parallel processes via the purrr 📦 in
smooth_estimates()andbasis(), though it is of limited use in the latter. Parallel processing will operate if a call tomirai::daemons()has been issued in the current R session.Rug plots in
draw.gam()now only show the unique data values to avoid needless overplotting. This behaviour is controlled via new argumentdistinct_rug. Setting this toFALSEwill get the previous behaviour.simulate.gam()gains aprint()method and thus no longer prints its attributes.citation("gratia")now suggests to use Simpson (2024) Journal of Open Source Software 9(104), 9862, when citing the package.simulate.gam()now returns a data frame, bringing it into line withstats::simulate.lm().With soap film smooths,
draw.gam()no longer plots points that are deemed outside the boundary of the soap film (as determined bymgcv::inSide()).smooth_estimates()continues to return these points however, because it might be confusing to suddenly lose evaluation points. This behaviour can be controlled by the argumentclip, which is available todraw.gam()andsmooth_estimates.gam()currently.draw.compare_smooths()now uses “Partial effect” as the y-axis label, in common with other partial effect plots in gratia.
New features
assemble()is a new generic function for assembling sets of plots from model objects. It is effectivelydraw()but without actually plotting on the current device. Instead it returns a list ofggplotobjects. Currently, a method for"gam"models,assemble.gam(), is provided whichdraw.gam()uses. Part of the wish of @ha0ye #35appraise()withmethod = "simulate"can now handle mgcv’s multivariate normal models fitted withfamily = mvn()and Tweedie location scale models fitted withfamily = twlss().-
fix_family_rd()is an (currently) internal function that extendsmgcv::fix.family.rd(). This function adds arfoo()function to the$rdcomponent of thefamily()object stored in the model. This function is used to generate new values of the response at supplied values of the linear predictor.fix_family_rd()callsmgcv::fix.family.rd()so it is backward compatible with mgcv’s behaviour, but it is designed to extend the behaviour through support for a richer set of models.Currently,
fix_family_rd()adds support for multivariate normal models fitted withfamily = mvn()and location-scale Tweedie models fitted withfamily = twlss(), but the latter is currently slow.The functionality of
fix_family_rd()may move to another package or even to mgcv if suitable. -
difference_smooths()can now be used to compare named smooths usingselect = c("s(x):f1", "s(x):f2")etc, where the vector of smooth names must match exactly something returned bysmooths(). Smooths to be compared must have the same covariate (xin the example) and same factor-by variable (fin the example). Tensor product factor-by smooths are handled likewise. This effectively handles the problem of #315, reported by @3rd3.Additionally,
difference_smooths()withgroup_means = TRUEcan now include group means specified using a random effect smooth, e.g. following the above example forselect, a random effect smooths(f, bs = "re"), with names(f), is looked for in the model matrix and its effects included in the comparisons. data_slice()gains argument.observed_onlywhich allows simple filtering of the combinations of values specified in the slice to those that are in the data frame supplied or in the model frame of a fitted GAM.posterior_samples(),predicted_samples(),fitted_samples(), andsimulate.gam()now simulate for all linear predictors (i.e., all responses) inmvn()andmultinom()models as these are all location parameter linear predictors.fitted_values()now works for GAMs fitted with familiesziP(),mvn(), andmultinom(). The non-working offitted-values()forziP()models was reported in #341 by @rroyauteposterior_samples(),fitted_samples(),predicted_samples(),derivatives_samples(), andresponse_derivatives()now all work with models fitted byscam::scam().basis()can now take a vector of coefficients for the basis functions when using the default method:basis(s(x), data = df, coefficients = rnorm(10)). Wish of #136draw.gam()anddraw.smooth_estimates()can now handle soap film smooths with known boundary values, and with nested boundaries.scale_fill_partial_effect()is a ggplot scale function that implements the default diverging red-blue gradient used by gratia when plotting partial effect surfaces for multivariate smooths.quantile_residuals()computes probability integral transform (PIT) and randomised quantile residuals for some GAMs and GLMs. Currently only models fitted with agaussian(),binomial(),Gamma(), orpoisson()family are supported.residuals_linpred_plot()andresiduals_hist_plot()can now use PIT or randomised quantile residuals in their diagnostic plots.
Bug fixes
conditional_values()would fail if a variable it was conditioning on was also a name of a function. #323 (but not really fixed when this was initially closed)parametric_effects()was only keeping one set of factor levels when there were multiple parametric factor terms in a model. Reported by @tamas-ferenci as part of discussion to #284mh_draws()would fail in the case of drawing onlyn = 1samples. #328 Reported by @zsussweinsimulate.gam()now works for theocat()family, which has a non-standardrdfunction in itsfamily()object. Reported by @hhp94, #319gaussian_draws()would fail in some cases with gamm4 models because the coefficients were returned as a vector, not the expected matrix. #332 reported by @JaredStufft-Eliondraw.smooth_estimates()would generate very many warnings when plotting spline on the sphere smoothers (bs = "sos") becausegeom_tile()was creating tiles that extended beyond valid geographical coordinates for the tile centre coordinates that it was being provided. The function that creates the data to evaluate the spline at now tries to avoid this. Note this fix is not a complete solution. #334 Reported by @StefanoMezzinilink()andinv_link()failed to extract the link an inverse link functions formvn()andmultinom()models.link()andinv_link()now work correctly for models fitted with theziP()family. #341 Reported by @rroyautebasis.scam()was incorrectly trying to identify the smooths named inselect.basis.scam()would fail if the SCAM contained any non-constrained (i.e. ordinary) smooths.overview()was displaying more significant digits in the p values than it was accurate to in terms of reporting p values as “<0.001”. A new argumentdigitscontrols how many digits are used when formatting p values, with default of3.theta()now works for models fitted with thegfam()family. Previously it would fail because it assumes allfamily()$getThetafunctions had an argumenttransto transform the theta values to the correct scale.overview()was not showing the model intercept, and was displaying slightly different results from those shown bysummary.gam().smooth_estimates()was not adding any known boundary condition that was part of a soap film smooth.draw.gamlss()(forGJRM::gamlss()models) now doesn’t fail with an error if there is more than a single smooth in any of the linear predictors.
gratia 0.10.0
CRAN release: 2024-12-19
New features
conditional_values()and itsdraw()method compute and plot predictions from a fitted GAM that are conditional on one or more covariates. The function is a wrapper aroundfitted_values()but allows the user simple ways to specify which covariates to condition on and at what values those covariates should take. It provides similar functionality tomarginaleffects::plot_predictions(), but is simpler. See #300.penalty()andbasis()can now allow the smooth to be reparameterized such that the resulting basis has an identity matrix. This more clearly highlights the penalty null space, the functions that the penalty has no effect on.draw.gam()anddraw.smooth_estimates()gain argumentcaption, which, if set toFALSEwill not plot the smooth basis type as a caption on the plot. #307appraise()andqq_plot.gam()now allow the user to set a random seed that is used when generating reference quantiles withmethod = "uniform"ormethod = "simulate".
Bug fixes
derivative_samples()was ignoring thescaleargument. #293 Reported by @jonathonmellorArgument
leveltoderivative_samples()was included accidentally. As of v0.9.2.9002 this argument is deprecated and using it will now generate a warning. #291draw()was not plotting cyclic P spline smooths. Reported by @Zuckerbrot #297derivatives()would fail for"fs"smooths with other parametric effects in the model. Reported by @mahonmb #301Partial residuals in
partial_residuals()anddraw.gam()were wrong for GAMs fitted withfamily = binomial()where theweightsargument contained the binomial sample sizes because the prior weights were being used to form weighted working residuals. Now working weights are used instead. Reported by @emchuron #273Internal function
gammals_link()was expecting"theta"as a synonym for the scale parameter but the master table has"phi"coded as the synonym. Now both work as expected.level()assumed thatlevelwould have only a single value even though it could handle multiple levels. #321
gratia 0.9.2
CRAN release: 2024-06-25
Breaking changes
-
parametric_effects()slightly escaped the great renaming that happened for 0.9.0. Columnstypeandtermdid not gain a prefix.. This is now rectified and these two columns are now.typeand.term.
User visible changes
Plots of random effects are now labelled with their smooth label. Previously, the title was taken fro the variable involved in the smooth, but this doesn’t work for terms like
s(subject, continuous_var, bs = "re")for random slopes, which previously would have the title"subject". Now such terms will have title"s(subject,continuous_var)". Simple random intercept terms,s(subject, bs = "re"), are now titled"s(subject)". #287-
The vignettes
-
custom-plotting.Rmd, and -
posterior-simulation.Rmdwere moved tovignettes/articlesand thus are no longer available as package vignettes. Instead, they are accessible as Articles through the package website: https://gavinsimpson.github.io/gratia/
-
New features
-
fitted_samples()now works forgam()models with multiple linear predictors, but currently only the location parameter is supported. The parameter is indicated through a new variable.parameterin the returned object.
Bug fixes
partial_residuals()was computing partial residuals from the deviance residuals. For compatibility withmgcv::plot.gam(), partial residuals are now computed from the working residuals. Reported by @wStockhausen #273appraise()was not passing theci_colargument onqq_plot()andworm_plot(). Reported by Sate Ahmed.Couldn’t pass
mvn_methodon to posterior sampling functions from user facing functionsfitted_samples(),posterior_samples(),smooth_samples(),derivative_samples(), andrepsonse_derivatives(). Reported by @stefgehrig #279fitted_values()works again for quantile GAMs fitted byqgam().confint.gam()was not applyingshiftto the estimate and upper and lower interval. #280 reported by @TIMAVID & @rbenthamparametric_effects()anddraw.parametric_effects()would forget about the levels of factors (intentionally), but this would lead to problems with ordered factors where the ordering of levels was not preserved. Now,parametric_effects()returns a named list of factor levels as attribute"factor_levels"containing the required information and the order of levels is preserved when plotting. #284 Reported by @mhpobparametric_effects()would fail if there were parametric terms in the model but they were all interaction terms (which we don’t currently handle). #282
gratia 0.9.0
CRAN release: 2024-03-27
Breaking changes
-
Many functions now return objects with different named variables. In order to avoid clashes with variable names used in user’s models or data, a period (
.) is now being used as a prefix for generated variable names. The functions whose names have changed are:smooth_estimates(),fitted_values(),fitted_samples(),posterior_samples(),derivatives(),partial_derivatives(), andderivative_samples(). In addition,add_confint()also adds newly-named variables.1. `est` is now `.estimate`, 2. `lower` and `upper` are now `.lower_ci` and `.upper_ci`, 3. `draw` and `row` and now `.draw` and `.row` respectively, 4. `fitted`, `se`, `crit` are now `.fitted`, `.se`, `.crit`, respectively 5. `smooth`, `by`, and `type` in `smooth_estimates()` are now `.smooth`, `.by`, `.type`, respectively. derivatives()andpartial_derivatives()now work more likesmooth_estimates(); in place of thevaranddatacolumns, gratia now stores the data variables at which the derivatives were evaluated as columns in the object with their actual variable names.-
The way spline-on-the-sphere (SOS) smooths (
bs = "sos") are plotted has changed to useggplot2::coord_sf()instead of the previously-usedggplot2::coord_map(). This changed has been made as a result ofcoord_map()being soft-deprecated (“superseded”) for a few minor versions of ggplot2 by now already, and changes to the guides system in version 3.5.0 of ggplot2.The axes on plots created with
coord_map()never really worked correctly and changing the angle of the tick labels never worked. Ascoord_map()is superseded, it didn’t receive the updates to the guides system and a side effect of these changes, the code that plotted SOS smooths was producing a warning with the release of ggplot2 version 3.5.0.The projection settings used to draw SOS smooths was previously controlled via arguments
projectionandorientation. These arguments do not affectggplot2::coord_sf(), Instead the projection used is controlled through new argumentcrs, which takes a PROJ string detailing the projection to use or an integer that refers to a known coordinate reference system (CRS). The default projection used is+proj=ortho +lat_0=20 +lon_0=XXwhereXXis the mean of the longitude coordinates of the data points.
Defunct and deprecated functions and arguments
Defunct
-
evaluate_smooth()was deprecated in gratia version 0.7.0. This function and all it’s methods have been removed from the package. Usesmooth_estimates()instead.
Deprecated functions
The following functions were deprecated in version 0.9.0 of gratia. They will eventually be removed from the package as part of a clean up ahead of an eventual 1.0.0 release. These functions will become defunct by version 0.11.0 or 1.0.0, whichever is released soonest.
evaluate_parametric_term()has been deprecated. Useparametric_effects()instead.datagen()has been deprecated. It never really did what it was originally designed to do, and has been replaced bydata_slice().
Deprecated arguments
To make functions in the package more consistent, the arguments select, term, and smooth are all used for the same thing and hence the latter two have been deprecated in favour of select. If a deprecated argument is used, a warning will be issued but the value assigned to the argument will be assigned to select and the function will continue.
User visible changes
-
smooth_samples()now uses a single call to the RNG to generate draws from the posterior of smooths. Previous to version 0.9.0,smooth_samples()would do a separate call tomvnfast::rmvn()for each smooth. As a result, the result of a call tosmooth_samples()on a model with multiple smooths will now produce different results to those generated previously. To regain the old behaviour, addrng_per_smooth = TRUEto thesmooth_samples()call.Note, however, that using per-smooth RNG calls with
method = "mh"will be very inefficient as, with that method, posterior draws for all coefficients in the model are sampled at once. So, only userng_per_smooth = TRUEwithmethod = "gaussian". -
The output of
smooth_estimates()and itsdraw()method have changed for tensor product smooths that involve one or more 2D marginal smooths. Now, if no covariate values are supplied via thedataargument,smooth_estimates()identifies if one of the marginals is a 2d surface and allows the covariates involved in that surface to vary fastest, ahead of terms in other marginals. This change has been made as it provides a better default when nothing is provided todata.This also affects
draw.gam(). fitted_values()now has some level of support for location, scale, shape families. Supported families aremgcv::gaulss(),mgcv::gammals(),mgcv::gumbls(),mgcv::gevlss(),mgcv::shash(),mgcv::twlss(), andmgcv::ziplss().gratia now requires dplyr versions >= 1.1.0 and tidyselect >= 1.2.0.
A new vignette Posterior Simulation is available, which describes how to do posterior simulation from fitted GAMs using {gratia}.
New features
Soap film smooths using basis
bs = "so"are now handled bydraw(),smooth_estimates()etc. #8response_derivatives()is a new function for computing derivatives of the response with respect to a (continuous) focal variable. First or second order derivatives can be computed using forward, backward, or central finite differences. The uncertainty in the estimated derivative is determined using posterior sampling viafitted_samples(), and hence can be derived from a Gaussian approximation to the posterior or using a Metropolis Hastings sampler (see below.)derivative_samples()is the work horse function behindresponse_derivatives(), which computes and returns posterior draws of the derivatives of any additive combination of model terms. Requested by @jonathanmellor #237data_sim()can now simulate response data from gamma, Tweedie and ordered categorical distributions.data_sim()gains two new example models"gwf2", simulating data only from Gu & Wahba’s f2 function, and"lwf6", example function 6 from Luo & Wahba (1997 JASA 92(437), 107-116).data_sim()can also simulate data for use with GAMs fitted usingfamily = gfam()for grouped families where different types of data in the response are handled. #266 and part of #265fitted_samples()andsmooth_samples()can now use the Metropolis Hastings sampler frommgcv::gam.mh(), instead of a Gaussian approximation, to sample from the posterior distribution of the model or specific smooths respectively.posterior_samples()is a new function in the family offitted_samples()andsmooth_samples().posterior_samples()returns draws from the posterior distribution of the response, combining the uncertainty in the estimated expected value of the response and the dispersion of the response distribution. The difference betweenposterior_samples()andpredicted_samples()is that the latter only includes variation due to drawing samples from the conditional distribution of the response (the uncertainty in the expected values is ignored), while the former includes both sources of uncertainty.fitted_samples()can new use a matrix of user-supplied posterior draws. Related to #120add_fitted_samples(),add_predicted_samples(),add_posterior_samples(), andadd_smooth_samples()are new utility functions that add the respective draws from the posterior distribution to an existing data object for the covariate values in that object:obj |> add_posterior_draws(model). #50basis_size()is a new function to extract the basis dimension (number of basis functions) for smooths. Methods are available for objects that inherit from classes"gam","gamm", and"mgcv.smooth"(for individual smooths).data_slice()gains a method for data frames and tibbles.typical_values()gains a method for data frames and tibbles.fitted_values()now works with models fitted using themgcv::ocat()family. The predicted probability for each category is returned, alongside a Wald interval created using the standard error (SE) of the estimated probability. The SE and estimated probabilities are transformed to the logit (linear predictor) scale, a Wald credible interval is formed, which is then back-transformed to the response (probability) scale.fitted_values()now works for GAMMs fitted usingmgcv::gamm(). Fitted (predicted) values only use the GAM part of the model, and thus exclude the random effects.link()andinv_link()work for models fitted using thecnorm()family.A worm plot can now be drawn in place of the QQ plot with
appraise()via new argumentuse_worm = TRUE. #62smooths()now works for models fitted withmgcv::gamm().overview()now returns the basis dimension for each smooth and gains an argumentstarswhich ifTRUEadd significance stars to the output plus a legend is printed in the tibble footer. Part of wish of @noamross #214New
add_constant()andtransform_fun()methods forsmooth_samples().evenly()gains argumentslowerandupperto modify the lower and / or upper bound of the interval over which evenly spaced values will be generated.add_sizer()is a new function to add information on whether the derivative of a smooth is significantly changing (where the credible interval excludes 0). Currently, methods forderivatives()andsmooth_estimates()objects are implemented. Part of request of @asanders11 #117draw.derivatives()gains argumentsadd_changeandchange_typeto allow derivatives of smooths to be plotted with indicators where the credible interval on the derivative excludes 0. Options allow for periods of decrease or increase to be differentiated viachange_type = "sizer"instead of the defaultchange_type = "change", which emphasises either type of change in the same way. Part of wish of @asanders11 #117-
draw.gam()can now group factor by smooths for a given factor into a single panel, rather than plotting the smooths for each level in separate panels. This is achieved via new argumentgrouped_by. Requested by @RPanczak #89draw.smooth_estimates()can now also group factor by smooths for a given factor into a single panel. The underlying plotting code used by
draw_smooth_estimates()for most univariate smooths can now add change indicators to the plots of smooths if those change indicators are added to the object created bysmooth_estimates()usingadd_sizer(). See the example in?draw.smooth_estimates.-
smooth_estimates()can, when evaluating a 3D or 4D tensor product smooth, identify if one or more 2D smooths is a marginal of the tensor product. If users do not provide covariate values at which to evaluate the smooths,smooth_estimates()will focus on the 2D marginal smooth (or the first if more than one is involved in the tensor product), instead of following the ordering of the terms in the definition of the tensor product. #191For example, in
te(z, x, y, bs = c(cr, ds), d = c(1, 2)), the second marginal smooth is a 2D Duchon spline of covariatesxandy. Previously,smooth_estimates()would have generatednvalues each forzandxandn_3dvalues fory, and then evaluated the tensor product at all combinations of those generated values. This would ignore the structure implicit in the tensor product, where we are likely to want to know how the surface estimated by the Duchon spline ofxandysmoothly varies withz. Previouslysmooth_estimates()would generate surfaces ofzandx, varying byy. Now,smooth_estimates()correctly identifies that one of the marginal smooths of the tensor product is a 2D surface and will focus on that surface varying with the other terms in the tensor product.This improved behaviour is needed because in some
bam()models it is not always possible to do the obvious thing and reorder the smooths when defining the tensor product to bete(x, y, z, bs = c(ds, cr), d = c(2, 1)). Whendiscrete = TRUEis used withbam()the terms in the tensor product may get rearranged during model setup for maximum efficiency (See Details in?mgcv::bam).Additionally,
draw.gam()now also works the same way. New function
null_deviance()that extracts the null deviance of a fitted model.draw(),smooth_estimates(),fitted_values(),data_slice(), andsmooth_samples()now all work for models fitted withscam::scam(). Where it matters, current support extends only to univariate smooths.generate_draws()is a new low-level function for generating posterior draws from fitted model coefficients.generate_daws()is an S3 generic function so is extensible by users. Currently provides a simple interface to a simple Gaussian approximation sampler (gaussian_draws()) and the simple Metropolis Hastings sample (mh_draws()) available viamgcv::gam.mh(). #211smooth_label()is a new function for extracting the labels ‘mgcv’ creates for smooths from the smooth object itself.penalty()has a default method that works withs(),te(),t2(), andti(), which create a smooth specification.transform_fun()gains argumentconstantto allow for the addition of a constant value to objects (e.g. the estimate and confidence interval). This enables a singleobj |> transform_fun(fun = exp, constant = 5)instead of separate calls toadd_constant()and thentransform_fun(). Part of the discussion of #79model_constant()is a new function that simply extracts the first coefficient from the estimated model.
Bug fixes
-
link(),inv_link(), and related family functions for theocat()weren’t correctly identifying the family name and as a result would throw an error even when passed an object of the correct family.link()andinv_link()now work correctly for thebetar()family in a fitted GAM. The
print()method forlp_matrix()now converts the matrix to a data frame before conversion to a tibble. This makes more sense as it results in more typical behaviour as the columns of the printed object are doubles.Constrained factor smooths (
bs = "sz") where the factor is not the first variable mentioned in the smooth (i.e.s(x, f, bs = "sz")for continuousxand factorf) are now plottable withdraw(). #208parametric_effects()was unable to handle special parametric terms likepoly(x)orlog(x)in formulas. Reported by @fhui28 #212parametric_effects()now works better for location, scale, shape models. Reported by @pboesu #45parametric_effectsnow works when there are missing values in one or more variables used in a fitted GAM. #219response_derivatives()was incorrectly using.datawith tidyselect selectors.typical_values()could not handle logical variables in a GAM fit as mgcv stores these as numerics in thevar.summary. This affectedevenly()anddata_slice(). #222parametric_effects()would fail when two or more ordered factors were in the model. Reported by @dsmi31 #221Continuous by smooths were being evaluated with the median value of the
byvariable instead of a value of 1. #224fitted_samples()(and henceposterior_samples()) now handles models with offset terms in the formula. Offset terms supplied via theoffsetargument are ignored bymgcv:::predict.gam()and hence are ignored also bygratia. Reported by @jonathonmellor #231 #233smooth_estimates()would fail on a"fs"smooth when a multivariate base smoother was used and the factor was not the last variable specified in the definition of the smooth:s(x1, x2, f, bs = "fs", xt = list(bs = "ds"))would work, buts(f, x1, x2, bs = "fs", xt = list(bs = "ds"))(or any ordering of variables that places the factor not last) would emit an obscure error. The ordering of the terms involved in the smooth now doesn’t matter. Reported by @chrisaak #249.draw.gam()would fail when plotting a multivariate base smoother used in an"sz"smooth. Now, this use case is identified and a message printed indicating that (currently) gratia doesn’t know how to plot such a smooth. Reported by @chrisaak #249.draw.gam()would fail when plotting a multivariate base smoother used in an"fs"smooth. Now, this use case is identified and a message printed indicating that (currently) gratia doesn’t know how to plot such a smooth. Reported by @chrisaak #249.derivative_samples()would fail withorder = 2and was only computing forward finite differences, regardless oftypefororder = 1. Partly reported by @samlipworth #251.The
draw()method forpenalty()was normalizing the penalty to the range 0–1, not the claimed and documented -1–1 with argumentnormalize = TRUE. This is now fixed.smooth_samples()was failing whendatawas supplied that contained more variables than were used in the smooth that was being sampled. Hence this generally fail unless a single smooth was being sampled from or the model contained only a single smooth. The function never intended to retain all the variables indatabut was written in such a way that it would fail when relocating the data columns to the end of the posterior sampling object. #255draw.gam()anddraw.smooth_estimates()would fail when plotting a univariate tensor product smooth (e.g.te(x),ti(x), ort2()). Reported by @wStockhausen #260plot.smooth()was not printing the factor level in subtitles for ordered factor by smooths.
gratia 0.8.1
CRAN release: 2023-02-02
User visible changes
smooth_samples()now returns objects with variables involved in smooths that have their correct name. Previously variables were named.x1,.x2, etc. Fixing #126 and improving compatibility withcompare_smooths()andsmooth_estimates()allowed the variables to be named correctly.gratia now depends on version 1.8-41 or later of the mgcv package.
New features
-
draw.gam()can now handle tensor products that include a marginal random effect smooth. Beware plotting such smooths if there are many levels, however, as a separate surface plot will be produced for each level.
Bug fixes
Additional fixes for changes in dplyr 1.1.0.
smooth_samples()now works when sampling from posteriors of multiple smooths with different dimension. #126 reported by @Aariq
gratia 0.8.0
User visible changes
{gratia} now depends on R version 4.1 or later.
A new vignette “Data slices” is supplied with {gratia}.
-
Functions in {gratia} have harmonised to use an argument named
datainstead ofnewdatafor passing new data at which to evaluate features of smooths. A message will be printed ifnewdatais used from now on. Existing code does not need to be changed asdatatakes its value fromnewdata.Note that due to the way
...is handled in R, if your R script uses thedataargument, and is run with versions of gratia prior to 8.0 (when released; 0.7.3.8 if using the development version) the user-supplied data will be silently ignored. As such, scripts usingdatashould check that the installed version of gratia is >= 0.8 and package developers should update to depend on versions >= 0.8 by usinggratia (>= 0.8)inDESCRIPTION. The order of the plots of smooths has changed in
draw.gam()so that they again match the order in which smooths were specified in the model formula. See Bug Fixes below for more detail or #154.
New features
Added basic support for GAMLSS (distributional GAMs) fitted with the
gamlss()function from package GJRM. Support is currently restricted to adraw()method.-
difference_smooths()can now include the group means in the difference, which many users expected. To include the group means usegroup_means = TRUEin the function call, e.g.difference_smooths(model, smooth = "s(x)", group_means = TRUE). Note: this function still differs fromplot_diff()in package itsadug, which essentially computes differences of model predictions. The main practical difference is that other effects beyond the factor by smooth, including random effects, may be included withplot_diff().This implements the main wish of #108 (@dinga92) and #143 (@mbolyanatz) despite my protestations that this was complicated in some cases (it isn’t; the complexity just cancels out.)
-
data_slice()has been totally revised. Now, the user provides the values for the variables they want in the slice and any variables in the model that are not specified will be held at typical values (i.e. the value of the observation that is closest to the median for numeric variables, or the modal factor level.)Data slices are now produced by passing
name=valuepairs for the variables and their values that you want to appear in the slice. For examplem <- gam(y ~ s(x1) + x2 + fac) data_slice(model, x1 = evenly(x1, n = 100), x2 = mean(x2))The
valuein the pair can be an expression that will be looked up (evaluated) in thedataargument or the model frame of the fitted model (the default). In the above example, the resulting slice will be a data frame of 100 observations, comprisingx1, which is a vector of 100 values spread evenly over the range ofx1, a constant value of the mean ofx2for thex2variable, and a constant factor level, the model class offac, for thefacvariable of the model. partial_derivatives()is a new function for computing partial derivatives of multivariate smooths (e.g.s(x,z),te(x,z)) with respect to one of the margins of the smooth. Multivariate smooths of any dimension are handled, but only one of the dimensions is allowed to vary. Partial derivatives are estimated using the method of finite differences, with forward, backward, and central finite differences available. Requested by @noamross #101overview()provides a simple overview of model terms for fitted GAMs.The new
bs = "sz"basis that was released with mgcv version 1.18-41 is now supported insmooth_estimates(),draw.gam(), anddraw.smooth_estimates()and this basis has its own unique plotting method. #202-
basis()now has a method for fitted GAM(M)s which can extract the estimated basis from the model and plot it, using the estimated coefficients for the smooth to weight the basis. #137There is also a new
draw.basis()method for plotting the results of a call tobasis(). This method can now also handle bivariate bases.tidy_basis()is a lower level function that does the heavy lifting inbasis(), and is now exported.tidy_basis()returns a tidy representation of a basis supplied as an object inheriting from class"mgcv.smooth". These objects are returned in the$smoothcomponent of a fitted GAM(M) model. lp_matrix()is a new utility function to quickly return the linear predictor matrix for an estimated model. It is a wrapper topredict(..., type = "lpmatrix")evenly()is a synonym forseq_min_max()and is preferred going forward. Gains argumentbyto produce sequences over a covariate that increment in units ofby.ref_level()andlevel()are new utility functions for extracting the reference or a specific level of a factor respectively. These will be most useful when specifying covariate values to condition on in a data slice.model_vars()is a new, public facing way of returning a vector of variables that are used in a model.difference_smooths()will now use the user-supplied data as points at which to evaluate a pair of smooths. Also note that the argumentnewdatahas been renameddata. #175The
draw()method fordifference_smooths()now uses better labels for plot titles to avoid long labels with even modest factor levels.derivatives()now works for factor-smooth interaction ("fs") smooths.draw()methods now allow the angle of tick labels on the x axis of plots to be rotated using argumentangle. Requested by @tamas-ferenci #87draw.gam()and related functions (draw.parametric_effects(),draw.smooth_estimates()) now add the basis to the plot using a caption. #155smooth_coefs()is a new utility function for extracting the coefficients for a particular smooth from a fitted model.smooth_coef_indices()is an associated function that returns the indices (positions) in the vector of model coefficients (returned bycoef(gam_model)) of those coefficients that pertain to the stated smooth.draw.gam()now better handles patchworks of plots where one or more of those plots has fixed aspect ratios. #190
Bug fixes
draw.posterior_smoothsnow plots posterior samples with a fixed aspect ratio if the smooth is isotropic. #148derivatives()now ignores random effect smooths (for which derivatives don’t make sense anyway). #168confint.gam(...., method = "simultaneous")now works with factor by smooths whereparmis passed the full name of a specific smooths(x)faclevel.The order of plots produced by
gratia::draw.gam()again matches the order in which the smooths entered the model formula. Recent changes to the internals ofgratia::draw.gam()when the switch tosmooth_estimates()was undertaken lead to a change in behaviour resulting from the use ofdplyr::group_split(), and it’s coercion internally of a character vector to a factor. This factor is now created explicitly, and the levels set to the correct order. #154Setting the
distargument to set response or smooth values toNAif they lay too far from the support of the data in multivariate smooths, this would lead an incorrect scale for the response guide. This is now fixed. #193Argument
funtodraw.gam()was not being applied to any parametric terms. Reported by @grasshoppermouse #195draw.gam()was adding the uncertainty for all linear predictors to smooths whenoverall_uncertainty = TRUEwas used. Nowdraw.gam()only includes the uncertainty for those linear predictors in which a smooth takes part. #158partial_derivatives()works when provided with a single data point at which to evaluate the derivative. #199transform_fun.smooth_estimates()was addressing the wrong variable names when trying to transform the confidence interval. #201data_slice()doesn’t fail with an error when used with a model that contains an offset term. #198confint.gam()no longer usesevaluate_smooth(), which is soft deprecated. #167qq_plot()andworm_plot()could compute the wrong deviance residuals used to generate the theoretical quantiles for some of the more exotic families (distributions) available in mgcv. This also affectedappraise()but only for the QQ plot; the residuals shown in the other plots and the deviance residuals shown on the y-axis of the QQ plot were correct. Only the generation of the reference intervals/quantiles was affected.
gratia 0.7.3
CRAN release: 2022-05-09
User visible changes
- Plots of smooths now use “Partial effect” for the y-axis label in place of “Effect”, to better indicate what is displayed.
New features
confint.fderiv()andconfint.gam()now return their results as a tibble instead of a common-or-garden data frame. The latter mostly already did this.Examples for
confint.fderiv()andconfint.gam()were reworked, in part to remove some inconsistent output in the examples when run on M1 macs.
Bug fixes
-
compare_smooths()failed when passed non-standard model “names” likecompare_smooths(m_gam, m_gamm$gam)orcompare_smooths(l[[1]], l[[2]])even if the evaluated objects were valid GAM(M) models. Reported by Andrew Irwin #150
gratia 0.7.2
CRAN release: 2022-03-17
New features
draw.gam()anddraw.smooth_estimates()can now handle splines on the sphere (s(lat, long, bs = "sos")) with special plotting methods usingggplot2::coord_map()to handle the projection to spherical coordinates. An orthographic projection is used by default, with an essentially arbitrary (and northern hemisphere-centric) default for the orientation of the view.fitted_values()insures thatdata(and hence the returned object) is a tibble rather than a common or garden data frame.
Bug fixes
draw.posterior_smooths()was redundantly plotting duplicate data in the rug plot. Now only the unique set of covariate values are used for drawing the rug.data_sim()was not passing thescaleargument in the bivariate example setting ("eg2").draw()methods forgamm()andgamm4::gamm4()fits were not passing arguments on todraw.gam().draw.smooth_estimates()would produce a subtitle with data for a continuous by smooth as if it were a factor by smooth. Now the subtitle only contains the name of the continuous by variable.
gratia 0.7.1
Due to an issue with the size of the package source tarball, which wasn’t discovered until after submission to CRAN, 0.7.1 was never released.
New features
-
draw.gam()anddraw.smooth_estimates(): {gratia} can now handle smooths of 3 or 4 covariates when plotting. For smooths of 3 covariates, the third covariate is handled withggplot2::facet_wrap()and a set (defaultn= 16) of small multiples is drawn, each a 2d surface evaluated at the specified value of the third covariate. For smooths of 4 covariates,ggplot2::facet_grid()is used to draw the small multiples, with the default producing 4 rows by 4 columns of plots at the specific values of the third and fourth covariates. The number of small multiples produced is controlled by new argumentsn_3d(default =n_3d = 16) andn_4d(defaultn_4d = 4, yieldingn_4d * n_4d= 16 facets) respectively.This only affects plotting;
smooth_estimates()has been able to handle smooths of any number of covariates for a while.When handling higher-dimensional smooths, actually drawing the plots on the default device can be slow, especially with the default value of
n = 100(which for 3D or 4D smooths would result in 160,000 data points being plotted). As such it is recommended that you reducento a smaller value:n = 50is a reasonable compromise of resolution and speed. model_concurvity()returns concurvity measures frommgcv::concurvity()for estimated GAMs in a tidy format. The synonymconcrvity()is also provided. Adraw()method is provided which produces a bar plot or a heatmap of the concurvity values depending on whether the overall concurvity of each smooth or the pairwise concurvity of each smooth in the model is requested.draw.gam()gains argumentresid_col = "steelblue3"that allows the colour of the partial residuals (if plotted) to be changed.
Bug fixes
model_edf()was not using thetypeargument. As a result it only ever returned the default EDF type.add_constant()methods weren’t applying the constant to all the required variables.draw.gam(),draw.parametric_effects()now actually work for a model with only parametric effects. #142 Reported by @Nelson-Gonparametric_effects()would fail for a model with only parametric terms becausepredict.gam()returns empty arrays when passedexclude = character(0).
gratia 0.7.0
CRAN release: 2022-02-07
Major changes
-
draw.gam()now usessmooth_estimates()internally and consequently uses itsdraw()method and underlying plotting code. This has simplified the code compared toevaluate_smooth()and its methods, which will allow for future development and addition of features more easily than ifevaluate_smooth()had been retained.Similarly,
evaluate_parametric_terms()is now deprecated in favour ofparametric_effects(), which is also used internally bydraw.gam()if parametric terms are present in the model (andparametric = TRUE).While a lot of code has been reused so differences between plots as a result of this change should be minimal, some corner cases may have been missed. File an Issue if you notice something that has changed that you think shouldn’t.
draw.gam()now plots 2D isotropic smooths (TPRS and Duchon splines) with equally-scaled x and y coordinates usingcoord_equal(ratio = 1). Alignment of these plots will be a little different now when plotting models with multiple smooths. See Issue #81.
Deprecated functions
From version 0.7.0, the following functions are considered deprecated and their use is discouraged:
-
fderiv()is soft-deprecated in favour ofderivatives(), -
evaluate_smooth()is soft-deprecated in favour ofsmooth_estimates(), -
evaluate_parametric_term()is soft-deprecated in favour ofparametric_effects().
The first call to one of these functions will generate a warning, pointing to the newer, alternative, function. It is safe to ignore these warnings, but these deprecated functions will no longer receive updates and are thus at risk of being removed from the package at some future date. The newer alternatives can handle more types of models and smooths, especially so in the case of smooth_estimates().
New features
-
fitted_values()provides a tidy wrapper aroundpredict.gam()for generating fitted values from the model. New covariate values can be provided via argumentdata. A credible interval on the fitted values is returned, and values can be on the link (linear predictor) or response scale.Note that this function returns expected values of the response. Hence, “fitted values” is used instead of “predictions” in the case of new covariate values to differentiate these values from the case of generating new response values from a fitted model.
rootogram()and itsdraw()method produce rootograms as diagnostic plots for fitted models. Currently only for models fitted withpoisson(),nb(),negbin(),gaussian()families.-
New helper functions
typical_values(),factor_combos()anddata_combos()for quickly creating data sets for producing predictions from fitted models where some covariates are fixed at come typical or representative values.typical_values()is a new helper function to return typical values for the covariates of a fitted model. It returns the value of the observation closest to the median for numerical covariates or the modal level of a factor while preserving the levels of that factor.typical_values()is useful in preparing data slices or scenarios for which fitted values from the estimated model are required.factor_combos()extracts and returns the combinations of levels of factors found in data used to fit a model. Unliketypical_values(),factor_combos()returns all the combinations of factor levels observed in the data, not just the modal level. Optionally, all combinations of factor levels can be returned, not just those in the observed data.data_combos()combines returns the factor data fromfactor_combos()plus the typical values of numerical covariates. This is useful if you want to generate predictions from the model for each combination of factor terms while holding any continuous covariates at their median values. nb_theta()is a new extractor function that returns the theta parameter of a fitted negative binomial GAM (familiesnb()ornegbin()). Additionally,theta()andhas_theta()provide additional functionality.theta()is an experimental function for extracting any additional parameters from the model or family.has_theta()is useful for checking if any additional parameters are available from the family or model.edf()extracts the effective degrees of freedom (EDF) of a fitted model or a specific smooth in the model. Various forms for the EDF can be extracted.model_edf()returns the EDF of the overall model. If supplied with multiple models, the EDFs of each model are returned for comparison.-
draw.gam()can now show a “rug” plot on a bivariate smooth by drawing small points with high transparency over the smooth surface at the data coordinates.In addition, the rugs on plots of factor by smooths now show the locations of covariate values for the specific level of the factor and not over all levels. This better reflects what data were used to estimate the smooth, even though the basis for each smooth was set up using all of the covariate locations.
draw.gam()anddraw.smooth_estimates()now allow some aspects of the plot to be changed: the fill (but not colour) and alpha attributes of the credible interval, and the line colour for the smooth can now be specified using argumentsci_col,ci_alpha, andsmooth_colrespectively.Partial residuals can now be plotted on factor by smooths. To allow this, the partial residuals are filtered so that only residuals associated with a particular level’s smooth are drawn on the plot of the smooth.
smooth_estimates()usescheck_user_select_smooths()to handle user-specified selection of smooth terms. As such it is more flexible than previously, and allows for easier selection of smooths to evaluate.fixef()is now imported (and re-exported) from the nlme package, with methods for models fitted withgam()andgamm(), to extract fixed effects estimates from fitted models.fixed_effects()is an alias forfixef().The
draw()method forsmooth_samples()can now handle 2D smooths. Additionally, the number of posterior draws to plot can now be specified when plotting using new argumentn_samples, which will result inn_samplesdraws being selected at random from the set of draws for plotting. New argumentseedallows the selection of draws to be repeatable.
Bug fixes
smooth_estimates()was not filtering user-supplied data for the by level of the specific smooth when used with by factor smooths. This would result in the smooth being evaluated at all rows of the user-supplied data, and therefore would result innrow(user_data) * nlevels(by_variable)rows in the returned object instead ofnrow(user_data)rows.The
add_confint()method forsmooth_estimates()had the upper and lower intervals reversed. #107 Reported by @Aariqdraw.gam()andsmooth_estimates()were both ignoring thedistargument that allows covariate values that lie too far from the support of the data to be excluded when returning estimated values from the smooth and plotting it. #111 Reported by @Aariqsmooth_samples()with a factor by GAM would return samples for the first factor level only. Reported by @rroyaute in discussion of #121smooth_samples()would fail if the model contained random effect “smooths”. These are now ignored with a message when runningsmooth_samples(). Reported by @isabellaghement in #121link(),inv_link()were failing on models fitted withfamily = scat(). Reported by @Aariq #130
gratia 0.6.0
CRAN release: 2021-04-18
Major changes
-
The {cowplot} package has been replaced by the {patchwork} package for producing multi-panel figures in
draw()andappraise(). This shouldn’t affect any code that used {gratia} only, but if you passed additional arguments tocowplot::plot_grid()or used thealignoraxisarguments ofdraw()andappraise(), you’ll need to adapt code accordingly.Typically, you can simply delete the
alignoraxisarguments and {patchwork} will just work and align plots nicely. Any arguments passed via...tocowplot::plot_grid()will just be ignored bypatchwork::wrap_plots()unless those passed arguments match any of the arguments ofpatchwork::wrap_plots().
New features
The {patchwork} package is now used for multi-panel figures. As such, {gratia} no longer Imports from the {cowplot} package.
-
Worm plot diagnostic plots are available via new function
worm_plot(). Worm plots are detrended Q-Q plots, where deviation from the Q-Q reference line are emphasized as deviations around the line occupy the full height of the plot.worm_plot()methods are available for models of classes"gam","glm", and"lm". (#62) -
Smooths can now be compared across models using
compare_smooths(), and comparisons visualised with the associateddraw()method. (#85 @dill)This feature is a bit experimental; the returned object uses nested lists and may change in the future if users find this confusing.
The reference line in
qq_plot()withmethod = "normal"was previously drawn as a line with intercept 0 and slope 1, to match the other methods. This was inconsistent withstats::qqplot()which drew the line through the 1st and 3rd quartiles.qq_plot()withmethod = "normal"now uses this robust reference line. Reference lines for the other methods remain drawn with slope 1 and intercept 0.qq_plot()withmethod = "normal"now draws a point-wise reference band using the standard error of the order statistic.The
draw()method forpenalty()now plots the penalty matrix heatmaps in a more-logical orientation, to match how the matrices might be written down or printed to the R console.link(), andinv_link()now work for models fitted with thegumbls()andshash()families. (#84)extract_link()is a lower level utility function related tolink()andinv_link(), and is now exported.
User visible changes
The default method name for generating reference quantiles in
qq_plot()was changed from"direct"to"uniform", to avoid confusion with themgcv::qq.gam()help page description of the methods. Accordingly usingmethod = "direct"is deprecated and a message to this effect is displayed if used.The way smooths/terms are selected in
derivatives()has been switched to use the same mechanism asdraw.gam()’sselectargument. To get a partial match toterm, you now need to also specifypartial_match = TRUEin the call toderivatives().
Bug fixes
transform_fun()had a copy paste bug in the definition of the then generic. (#96 @Aariq)derivatives()with user-suppliednewdatawould fail for factor by smooths withinterval = "simultaneous"and would introduce rows with derivative == 0 withinterval = "confidence"because it didn’t subset the rows ofnewdatafor the specific level of the by factor when computing derivatives. (#102 @sambweber)evaluate_smooth()can now handle random effect smooths defined using an ordered factor. (#99 @StefanoMezzini)
gratia 0.5.1
CRAN release: 2021-01-23
New features
-
smooth_estimates()can now handle -
penalty()provides a tidy representation of the penalty matrices of smooths. The tidy representation is most suitable for plotting withggplot().A
draw()method is provided, which represents the penalty matrix as a heatmap.
User visible changes
- The
newdataargument tosmooth_estimates()has been changed todataas was originally intended.
gratia 0.5.0
CRAN release: 2021-01-10
New features
-
Partial residuals for models can be computed with
partial_residuals(). The partial residuals are the weighted residuals of the model added to the contribution of each smooth term (as returned bypredict(model, type = "terms").Also, new function
add_partial_residuals()can be used to add the partial residuals to data frames. -
Users can now control to some extent what colour or fill scales are used when plotting smooths in those
draw()methods that use them. This is most useful to change the fill scale when plotting 2D smooths, or to change the discrete colour scale used when plotting random factor smooths (bs = "fs").The user can pass scales via arguments
discrete_colourandcontinuous_fill. -
The effects of certain smooths can be excluded from data simulated from a model using
simulate.gam()andpredicted_samples()by passingexcludeortermson topredict.gam(). This allows for excluding random effects, for example, from model predicted values that are then used to simulate new data from the conditional distribution. See the example inpredicted_samples().Wish of #74 (@hgoldspiel)
-
draw.gam()and related functions gain argumentsconstantandfunto allow for user-defined constants and transformations of smooth estimates and confidence intervals to be applied.Part of wish of Wish of #79.
confint.gam()now works for 2D smooths also.smooth_estimates()is an early version of code to replace (or more likely supersede)evaluate_smooth().smooth_estimates()can currently only handle 1D smooths of the standard types.
User visible changes
-
The meaning of
parminconfint.gamhas changed. This argument now requires a smooth label to match a smooth. A vector of labels can be provided, but partial matching against a smooth label only works with a singleparmvalue.The default behaviour remains unchanged however; if
parmisNULLthen all smooths are evaluated and returned with confidence intervals. data_class()is no longer exported; it was only ever intended to be an internal function.
Bug Fixes
-
confint.gam()was failing on a tensor product smooth due to matching issues. Reported by @tamas-ferenci #88This also fixes #80
- which was a related issue with selecting a specific smooth.
The vdiffr package is now used conditionally in package tests. Reported by Brian Ripley #93
gratia 0.4.1
CRAN release: 2020-05-30
User visible changes
-
draw.gam()withscales = "fixed"now applies to all terms that can be plotted, including 2d smooths.Reported by @StefanoMezzini #73
Bug fixes
dplyr::combine()was deprecated. Switch tovctrs::vec_c().-
draw.gam()withscales = "fixed"wasn’t using fixed scales where 2d smooths were in the model.Reported by @StefanoMezzini #73
gratia 0.4.0
New features
draw.gam()can include partial residuals when drawing univariate smooths. Useresiduals = TRUEto add partial residuals to each univariate smooth that is drawn. This feature is not available for smooths of more than one variable, by smooths, or factor-smooth interactions (bs = "fs").-
The coverage of credible and confidence intervals drawn by
draw.gam()can be specified via argumentci_level. The default is arbitrarily0.95for no other reason than (rough) compatibility withplot.gam().This change has had the effect of making the intervals slightly narrower than in previous versions of gratia; intervals were drawn at ± 2 × the standard error. The default intervals are now drawn at ± ~1.96 × the standard error.
New function
difference_smooths()for computing differences between factor smooth interactions. Methods available forgam(),bam(),gamm()andgamm4::gamm4(). Also has adraw()method, which can handle differences of 1D and 2D smooths currently (handling 3D and 4D smooths is planned).New functions
add_fitted()andadd_residuals()to add fitted values (expectations) and model residuals to an existing data frame. Currently methods available for objects fitted bygam()andbam().data_sim()is a tidy reimplementation ofmgcv::gamSim()with the added ability to use sampling distributions other than the Gaussian for all models implemented. Currently Gaussian, Poisson, and Bernoulli sampling distributions are available.smooth_samples()can handle continuous by variable smooths such as in varying coefficient models.link()andinv_link()now work for all families available in mgcv, including the location, scale, shape families, and the more specialised families described in?mgcv::family.mgcv.evaluate_smooth(),data_slice(),family(),link(),inv_link()methods for models fitted usinggamm4()from the gamm4 package.data_slice()can generate data for a 1-d slice (a single variable varying).-
The colour of the points, reference lines, and simulation band in
appraise()can now be specified via arguments-
point_col, -
point_alpha, ci_colci_alphaline_col
These are passed on to
qq_plot(),observed_fitted_plot(),residuals_linpred_plot(), andresiduals_hist_plot(), which also now take the new arguments were applicable. -
Added utility functions
is_factor_term()andterm_variables()for working with models.is_factor_term()identifies is the named term is a factor using information from theterms()object of the fitted model.term_variables()returns a character vector of variable names that are involved in a model term. These are strictly for working with parametric terms in models.-
appraise()now works for models fitted byglm()andlm(), as do the underlying functions it calls, especiallyqq_plot.appraise()also works for models fitted with familygaulss(). Further location scale models and models fitted with extended family functions will be supported in upcoming releases.
User visible changes
datagen()is now an internal function and is no longer exported. Usedata_slice()instead.evaluate_parametric_term()is now much stricter and can only evaluate main effect terms, i.e. those whose order, as stored in thetermsobject of the model is1.
Bug fixes
The
draw()method forderivatives()was not getting the x-axis label for factor by smooths correctly, and instead was usingNAfor the second and subsequent levels of the factor.The
datagen()method for class"gam"couldn’t possibly have worked for anything but the simplest models and would fail even with simple factor by smooths. These issues have been fixed, but the behaviour ofdatagen()has changed, and the function is now not intended for use by users.Fixed an issue where in models terms of the form
factor1:factor2were incorrectly identified as being numeric parametric terms. #68
gratia 0.3.1
CRAN release: 2020-03-29
New features
-
New functions
link()andinv_link()to access the link function and its inverse from fitted models and family functions.Methods for classes:
"glm","gam","bam","gamm"currently. #58 Adds explicit
family()methods for objects of classes"gam","bam", and"gamm".derivatives()now handles non-numeric when creating shifted data for finite differences. Fixes a problem withstringsAsFactors = FALSEdefault in R-devel. #64
gratia 0.3.0
CRAN release: 2020-01-19
New features
-
gratia now uses the mvnfast package for random draws from a multivariate normal distribution (
mvnfast::rmvn()). Contributed by Henrik Singmann New function
basis()for generating tidy representations of basis expansions from an mgcv-like definition of a smooth, e.g.s(),te(),ti(), ort2(). The basic smooth types also have a simpledraw()method for plotting the basis.basis()is a simple wrapper aroundmgcv::smoothCon()with some post processing of the basis model matrix into a tidy format. #42New function
smooth_samples()to draw samples of entire smooth functions from their posterior distribution. Also has adraw()method for plotting the posterior samples.
Bug fixes
draw.gam()would produce empty plots between the panels for the parametric terms if there were 2 or more parametric terms in a model. Reported by @sklayn #39.-
derivatives()now works with factor by smooths, including ordered factor by smooths. The function also now works correctly for complex models with multiple covariates/smooths. #47derivatives()also now handles'fs'smooths. Reported by @tomand-uio #57. evaluate_parametric_term()and hencedraw.gam()would fail on aziplss()model because i) gratia didn’t handle parametric terms in models with multiple linear predictors correctly, and ii) gratia didn’t convert to the naming convention of mgcv for terms in higher linear predictors. Reported by @pboesu #45
