| Type: | Package |
| Title: | Combines Changepoint Analysis with 'ggplot2' |
| Version: | 0.4.0 |
| Description: | A unified, tidy, 'ggplot2'-native interface to changepoint detection in R. Provides the 'ggcpt' S3 result class with 'broom'-style tidy/glance/augment methods, 'autoplot()' (with confidence intervals, fitted signals, and multivariate facets), composable geoms ('geom_changepoint()', 'geom_cpt_segment()', 'geom_cpt_ci()', 'stat_changepoint()'), and a 'cpt_detect()' dispatcher covering over thirty methods with introspection via 'cpt_methods()': penalised/optimal partitioning (PELT, BinSeg, SegNeigh, AMOC, FPOP, CROPS penalty paths, 'fastcpd', change-in-slope via 'cpop'), multiscale and search methods (WBS, WBS2, NOT, MOSUM, Isolate-Detect, TGUH, SMUCE/HSMUCE with confidence intervals), nonparametric and kernel methods ('changepoint.np', 'ecp', 'kcpRS', 'CptNonPar', sequential 'cpm', self-normalisation via 'SNSeg'), Bayesian methods ('bcp', online 'ocp', 'Rbeast'), high-dimensional and multivariate methods ('InspectChangepoint', 'ocd', 'changepoint.geo'), regression breaks ('strucchange', 'segmented', 'EnvCpt'), and robust detection under drift and autocorrelation ('DeCAFS'). Also includes method comparison, batch/panel detection, bootstrap stability diagnostics, accuracy metrics, Bayesian posterior and run-length plots, interactive rendering, data simulation with canonical test signals, and per-method citations. |
| License: | GPL (≥ 3) |
| Encoding: | UTF-8 |
| Imports: | changepoint, changepoint.np, dplyr, ecp, generics, ggplot2 (≥ 3.4.0), lifecycle, Rdpack, stats, tibble, utils |
| RdMacros: | Rdpack |
| RoxygenNote: | 7.3.2 |
| Suggests: | rmarkdown, knitr, testthat (≥ 3.0.0), wbs, breakfast, not, mosum, fpop, IDetect, stepR, cpop, bcp, ocp, Rbeast, cpm, kcpRS, CptNonPar, DeCAFS, SNSeg, InspectChangepoint, ocd, changepoint.geo, strucchange, segmented, EnvCpt, fastcpd, plotly, future, future.apply |
| VignetteBuilder: | knitr |
| URL: | https://pursuitofdatascience.github.io/ggchangepoint/ |
| BugReports: | https://github.com/PursuitOfDataScience/ggchangepoint/issues |
| NeedsCompilation: | no |
| Packaged: | 2026-08-24 16:18:20 UTC; youzhi |
| Author: | Youzhi Yu [aut, cre] |
| Maintainer: | Youzhi Yu <yuyouzhi666@icloud.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-08-24 18:50:16 UTC |
ggchangepoint package
Description
Unified tidy changepoint detection with ggplot2 visualisation.
Details
ggchangepoint provides a consistent S3 result class (ggcpt)
for changepoint detection results, broom-style methods
(tidy(), glance(), augment()), ggplot2
integration via autoplot() and composable geoms
(geom_changepoint(), geom_cpt_segment(),
geom_cpt_ci(), stat_changepoint()), and a unified dispatcher
cpt_detect() that supports over thirty methods.
**Detection engines.** cpt_detect() currently dispatches to 31
methods across six families (run cpt_methods() for the live
table with installation status):
-
Penalised/optimal: PELT, BinSeg, SegNeigh, AMOC (changepoint); FPOP (fpop); the CROPS penalty path (
cpt_crops()); fastcpd (fastcpd, incl. AR/ARMA/GARCH); change-in-slope via CPOP (cpop). -
Multiscale/search: WBS (wbs), WBS2 and TGUH (breakfast), NOT (not), MOSUM incl. multiscale (mosum), Isolate-Detect (IDetect), SMUCE/HSMUCE with confidence intervals (stepR).
-
Nonparametric/kernel: NP (changepoint.np), E-Divisive/E-Agglo (ecp), kernel running statistics (kcpRS), NP-MOJO (CptNonPar), sequential CPM (cpm), self-normalisation (SNSeg).
-
Bayesian: Barry-Hartigan posterior (bcp), online BOCPD (ocp), BEAST model averaging (Rbeast).
-
Multivariate/high-dimensional: sparse projection (InspectChangepoint), online ocd (ocd), geometric mapping (changepoint.geo).
-
Regression breaks and robust detection: Bai-Perron breaks with CIs (strucchange), broken-line regression (segmented), changepoints-vs-autocorrelation model selection (EnvCpt), drift+AR robust detection (DeCAFS).
**Key features.** Every detector returns a ggcpt object with a stable
tibble(cp, cp_value) contract (plus engine extras such as
ci_lower/ci_upper and posterior_prob). Visualise any
result directly with autoplot() (confidence intervals, fitted
signals, multivariate facets), the Bayesian displays
(ggcpt_posterior(), ggcpt_runlength()), or interactively
via ggcpt_interactive(). Compare methods with
ggcpt_compare(); run panels of series with cpt_batch();
quantify uncertainty with cpt_stability(); sweep penalties with
cpt_crops(). Evaluate accuracy with cpt_metrics() and
ggcpt_eval(); simulate ground-truth data with
cpt_simulate() and the canonical test signals; and cite the
methodology behind any result with cpt_cite().
Author(s)
Maintainer: Youzhi Yu yuyouzhi666@icloud.com
See Also
Useful links:
Report bugs at https://github.com/PursuitOfDataScience/ggchangepoint/issues
Annotate segments with alternating shading
Description
Adds alternating shaded rectangles to highlight segments between changepoints.
Usage
annotate_segments(cp, n, fill = c("grey90", "white"), alpha = 0.5, ...)
Arguments
cp |
Changepoint indices (including 0 and n). |
n |
Length of the series. |
fill |
Colors for alternating segments. Defaults to c("grey90", "white"). |
alpha |
Alpha for fill. Defaults to 0.5. |
... |
Additional arguments passed to |
Value
A list of ggplot annotations.
Augment a ggcpt object
Description
Returns the original data with added columns: seg_id, .fitted,
.resid, and is_changepoint.
Usage
## S3 method for class 'ggcpt'
augment(x, ...)
Arguments
x |
A |
... |
Additional arguments (ignored). |
Details
For a multivariate result every coordinate is returned, but the
changepoints are shared across them, so seg_id and
is_changepoint apply to the whole row while .fitted and
.resid describe the first coordinate only — the same
coordinate $segments$param_estimate summarises. When an engine
supplies its own fitted signal (SMUCE, DeCAFS, cpop, segmented, bcp,
beast) that signal is used for .fitted in place of the segment
means.
Value
A tibble with the original data plus augment columns.
Autoplot a ggcpt object
Description
Renders a changepoint detection result as a ggplot. The raw series is drawn
as a line (with optional points), changepoints are shown as vertical lines,
and (optionally) fitted segment levels, the engine's fitted signal, and
changepoint-location confidence intervals are overlaid. Multivariate
results (from ecp, inspect, geomcp, ...) are drawn as
faceted small-multiples with shared changepoint rules.
Usage
## S3 method for class 'ggcpt'
autoplot(
object,
show_segments = FALSE,
show_ci = FALSE,
show_fit = FALSE,
cptline_alpha = 1,
cptline_color = "blue",
cptline_type = "solid",
cptline_linewidth = 0.5,
show_points = NULL,
show_line = TRUE,
index = NULL,
...
)
Arguments
object |
A |
show_segments |
Logical. Whether to draw the fitted segment means.
Defaults to |
show_ci |
Logical. Whether to draw confidence intervals for
changepoint locations, when the engine provides them (columns
|
show_fit |
Logical. Whether to draw the engine's fitted signal (the
|
cptline_alpha |
Alpha for changepoint lines. Defaults to |
cptline_color |
Color for changepoint lines. Defaults to |
cptline_type |
Linetype for changepoint lines. Defaults to |
cptline_linewidth |
Linewidth for changepoint lines. Defaults to |
show_points |
Logical. Whether to draw data points. Auto-off above 500 obs. |
show_line |
Logical. Whether to draw the line. Defaults to |
index |
Optional vector of x-axis values (e.g. dates) of the same length as the series; defaults to the observation index. |
... |
Unknown arguments are ignored with a warning. |
Value
A ggplot object.
Bayesian changepoint wrapper (Barry-Hartigan product partition model)
Description
Wraps bcp::bcp(), the MCMC implementation (Erdman and Emerson, 2007)
of the Barry and Hartigan (1993) product partition model. The engine
returns a posterior probability of a changepoint at every location;
locations whose posterior probability reaches prob_threshold are
reported as changepoints, and the full probability profile is kept so that
ggcpt_posterior() can draw the classic two-panel posterior
plot.
Usage
bcp_wrapper(x, prob_threshold = 0.5, burnin = 50, mcmc = 500, seed = NULL, ...)
Arguments
x |
A numeric vector. |
prob_threshold |
Posterior probability cutoff in |
burnin |
Number of burn-in MCMC iterations. Defaults to |
mcmc |
Number of post-burn-in MCMC iterations. Defaults to |
seed |
Optional seed for reproducibility of the MCMC run. |
... |
Additional arguments passed to |
Value
A ggcpt object. The changepoints tibble carries a
posterior_prob column, and the data tibble carries the
posterior mean in its fitted column.
References
Barry D, Hartigan JA (1993). “A Bayesian analysis for change point problems.” Journal of the American Statistical Association, 88(421), 309–319.
Erdman C, Emerson JW (2007). “bcp: An R package for performing a Bayesian analysis of change point problems.” Journal of Statistical Software, 23(3), 1–13.
Examples
res <- bcp_wrapper(c(rnorm(60), rnorm(60, 4)), seed = 2026)
res$changepoints
ggcpt_posterior(res)
BEAST wrapper — Bayesian estimation of abrupt change, seasonality, and trend
Description
Wraps Rbeast::beast() (Zhao et al., 2019), a Bayesian
model-averaging ensemble that estimates the number and location of trend
changepoints together with their posterior occurrence probabilities.
Locations whose posterior probability reaches prob_threshold are
reported; the probability profile renders via
ggcpt_posterior().
Usage
beast_wrapper(x, prob_threshold = 0.5, seed = NULL, ...)
Arguments
x |
A numeric vector (treated as a non-seasonal series). |
prob_threshold |
Posterior probability cutoff in |
seed |
Optional seed for the engine's MCMC sampler (passed to
|
... |
Additional arguments passed to |
Value
A ggcpt object. The changepoints tibble carries
posterior_prob, and the data tibble carries the posterior
mean trend in its fitted column.
References
Zhao K, Wulder MA, Hu T, Bright R, Wu Q, Qin H, Li Y, Toman E, Mallick B, Zhang X, Brown M (2019). “Detecting change-point, trend, and seasonality in satellite time series data to track abrupt changes and nonlinear dynamics: A Bayesian ensemble algorithm.” Remote Sensing of Environment, 232, 111181.
Examples
res <- beast_wrapper(c(rnorm(60), rnorm(60, 4)), seed = 2026)
res$changepoints
Bayesian online changepoint detection wrapper (BOCPD)
Description
Wraps ocp::onlineCPD(), an implementation of Bayesian Online
Changepoint Detection (Adams and MacKay, 2007). BOCPD recursively updates
a posterior over the current run length (time since the last
change); the maximum a posteriori set of changepoints is reported, and the
full run-length posterior is kept so that ggcpt_runlength()
can draw the signature run-length heatmap.
Usage
bocpd_wrapper(x, hazard = 100, ...)
Arguments
x |
A numeric vector. |
hazard |
Constant hazard rate |
... |
Additional arguments passed to |
Value
A ggcpt object with the MAP changepoint set. The full
ocp fit (including the run-length posterior) is kept in
$fit.
References
Adams RP, MacKay DJ (2007). “Bayesian online changepoint detection.” arXiv preprint arXiv:0710.3742.
Examples
res <- bocpd_wrapper(c(rnorm(60), rnorm(60, 4)))
res$changepoints
ggcpt_runlength(res)
Sequential change point model wrapper (CPM)
Description
Wraps cpm::processStream() (Ross, 2015) for distribution-free
sequential changepoint detection via repeated two-sample tests
(Mann-Whitney for location, Mood for scale, Lepage, Kolmogorov-Smirnov and
Cramer-von-Mises for general changes, and parametric Student/Bartlett/GLR
variants). Although the engine is designed for streams, it is run here
over the full series in one pass, mimicking online monitoring with average
run length arl0.
Usage
cpm_wrapper(x, cpm_type = "Mann-Whitney", arl0 = 500, startup = 20, ...)
Arguments
x |
A numeric vector. |
cpm_type |
Test statistic, passed to |
arl0 |
Target in-control average run length (how many observations,
on average, before a false alarm). Defaults to |
startup |
Number of observations after each restart before monitoring
begins. Defaults to |
... |
Additional arguments passed to |
Value
A ggcpt object. The changepoints tibble carries a
detection_time column: the index at which the sequential test
flagged each change (always later than the estimated location).
References
Ross GJ (2015). “Parametric and nonparametric sequential change detection in R: The cpm package.” Journal of Statistical Software, 66(3), 1–20.
Examples
res <- cpm_wrapper(c(rnorm(100), rnorm(100, 3)))
res$changepoints
CPOP wrapper — optimal change-in-slope detection
Description
Wraps cpop::cpop() (Fearnhead, Maidstone and Letchford, 2019;
Fearnhead and Grose, 2024): exact penalised estimation of a
continuous piecewise-linear mean via dynamic programming with
functional pruning. This is the engine behind
cpt_detect(change_in = "slope"). The fitted broken line is stored
in the fitted column and renders via
autoplot(show_fit = TRUE).
Usage
cpop_wrapper(x, penalty = NULL, sd = NULL, ...)
Arguments
x |
A numeric vector. |
penalty |
Penalty for adding a changepoint. Defaults to
|
sd |
Noise standard deviation; when |
... |
Additional arguments passed to |
Value
A ggcpt object with change_in = "slope". For a
continuous fit the reported location is the kink point itself.
References
Fearnhead P, Maidstone R, Letchford A (2019). “Detecting changes in slope with an L0 penalty.” Journal of Computational and Graphical Statistics, 28(2), 265–275.
Fearnhead P, Grose D (2024). “cpop: Detecting changes in piecewise-linear signals.” Journal of Statistical Software, 109(7), 1–30.
Examples
set.seed(2026)
y <- cumsum(c(rep(0.3, 100), rep(-0.4, 100))) + rnorm(200)
res <- cpop_wrapper(y)
res$changepoints
ggplot2::autoplot(res, show_fit = TRUE)
Batch changepoint detection over many series
Description
Runs one detector over every series in a collection — the panel-data loop
that methodological and applied work both need constantly. Accepts a
matrix/data frame (one column per series) or a named list of numeric
vectors. Honours future::plan() for parallel execution when the
future.apply package is available, with parallel-safe RNG.
Usage
cpt_batch(x, method = "pelt", change_in = "mean", seed = NULL, ...)
## S3 method for class 'ggcpt_batch'
print(x, ...)
## S3 method for class 'ggcpt_batch'
tidy(x, ...)
## S3 method for class 'ggcpt_batch'
autoplot(object, ...)
Arguments
x |
For |
method |
Detection method, passed to |
change_in |
What to detect change in, passed to
|
seed |
Optional seed for reproducible parallel execution (passed to
|
... |
Additional arguments passed to every |
object |
A |
Value
A ggcpt_batch object: a tibble with one row per series and
columns series, n_changepoints, changepoints (a
list-column of tidy tibbles), and result (a list-column of
ggcpt objects). Methods: print(), tidy() (one row
per changepoint across all series), and autoplot() (faceted
small-multiples with each series' changepoints).
Examples
set.seed(2026)
X <- cbind(a = c(rnorm(60), rnorm(60, 4)), b = rnorm(120))
batch <- cpt_batch(X, method = "pelt")
batch
tidy(batch)
ggplot2::autoplot(batch)
Cite the method behind a result
Description
Returns the bibliographic reference(s) for the method behind a
ggcpt result (or a method name), so an analysis can cite the right
methodological paper without leaving R.
Usage
cpt_cite(x)
Arguments
x |
A |
Value
A tibble with columns method and reference,
invisibly; the references are also printed.
Examples
cpt_cite("pelt")
res <- cpt_detect(c(rnorm(50), rnorm(50, 5)), method = "pelt")
cpt_cite(res)
CROPS — the full penalty path of a penalised changepoint method
Description
Runs PELT once per distinct optimal segmentation as the penalty
ranges over [pen_min, pen_max], using the CROPS algorithm of
Haynes, Eckley and Fearnhead (2017) as implemented by the
changepoint package. Instead of committing to one penalty, the
analyst sees every segmentation the data admits along the path, together
with its cost, and picks the elbow.
Usage
cpt_crops(
x,
change_in = c("mean", "var", "meanvar"),
pen_min = NULL,
pen_max = NULL,
...
)
## S3 method for class 'ggcpt_path'
autoplot(
object,
type = c("elbow", "path", "segmentations"),
max_facets = 12,
...
)
## S3 method for class 'ggcpt_path'
print(x, ...)
## S3 method for class 'ggcpt_path'
tidy(x, ...)
Arguments
x |
For |
change_in |
What to detect change in: |
pen_min, pen_max |
The penalty interval to sweep. Default to
|
... |
Additional arguments passed to the underlying
|
object |
A |
type |
Plot type for |
max_facets |
Maximum number of solutions shown by
|
Value
A ggcpt_path object: a list with a solutions tibble
(one row per distinct segmentation: penalty, n_cpts,
cost, and a cpts list-column), the data, and
metadata. Methods: print(), tidy(), and
autoplot() (elbow plot by default;
type = "path" for penalty vs. number of changepoints;
type = "segmentations" for the faceted segmentations).
References
Haynes K, Eckley IA, Fearnhead P (2017). “Computationally efficient changepoint detection for a range of penalties.” Journal of Computational and Graphical Statistics, 26(1), 134–143.
Killick R, Eckley I (2014). “changepoint: An R package for changepoint analysis.” Journal of statistical software, 58(3), 1–19.
Examples
set.seed(2026)
x <- c(rnorm(100), rnorm(100, 3), rnorm(100, -1))
path <- cpt_crops(x)
path
ggplot2::autoplot(path)
ggplot2::autoplot(path, type = "segmentations")
Unified changepoint detection dispatcher
Description
Runs a changepoint detection method on a sequence and returns a tidy
ggcpt result object. This is the recommended entry point for most
users. See cpt_methods() for the full method table with
engines and capabilities.
Usage
cpt_detect(x, method = "pelt", change_in = "mean", penalty = "MBIC", ...)
Arguments
x |
A numeric vector for univariate methods, or a numeric
matrix/data frame (rows are time points) for the multivariate methods
( |
method |
Detection method. One of |
change_in |
What to detect change in. One of |
penalty |
Penalty type or value. Either a character string
( |
... |
Additional arguments passed to the specific wrapper (see the
wrapper's help page for engine-specific options). Where an argument is
also derived from |
Value
A ggcpt object.
Scale sensitivity of the penalised change-in-mean engines
"pelt", "binseg", "segneigh" and "fpop"
compare a penalty against a raw segment cost when
change_in = "mean": changepoint's Normal cost assumes a
noise standard deviation of 1, and fpop's lambda is an
absolute penalty on the residual sum of squares. Neither rescales the
data, so on a series whose noise is much wider than 1 the penalty is
effectively negligible and the segmentation shatters. On one true
changepoint with a jump of five standard deviations, "pelt"
returns 1 changepoint at \sigma = 1, 29 at \sigma = 3 and
138 at \sigma = 10. Three ways to avoid it, in order of
convenience:
standardise the series first (
cpt_detect(scale(x)[, 1], method = "pelt"));pass a penalty on the data's own scale, for example
penalty = 2 * log(length(x)) * stats::var(diff(x)) / 2;use
change_in = "meanvar", which estimates a variance per segment and is unaffected.
The other engines are unaffected: SMUCE, WBS, WBS2, NOT, MOSUM, Isolate-Detect, TGUH, CPOP, DeCAFS and the Bayesian, nonparametric and multivariate methods all estimate or cancel the noise scale internally, and return the same segmentation whatever the units.
Examples
set.seed(2022)
x <- c(rnorm(100, 0, 1), rnorm(100, 10, 1))
result <- cpt_detect(x, method = "pelt", change_in = "mean")
result
ggplot2::autoplot(result)
Introspect available changepoint detection methods
Description
Returns a tibble describing every method the package knows about — those that are wired and those that are planned — along with their capabilities and installation status. Useful for discovering what can be run and what needs to be installed.
Usage
cpt_methods()
Value
A tibble with columns:
- method
Method name as passed to
cpt_detect().- change_in
What types of change the method can detect.
- engine
The upstream R package that implements the method.
- status
"available"(wired in this release) or"planned"(future).- installed
TRUEif the engine package is installed,FALSEif it is aSuggestsengine that is missing,NAfor planned methods.- target_release
What a planned method is waiting on: a release, or
"when on CRAN"when the engine package itself is not available from CRAN.NAfor methods that are already wired. Askingcpt_detect()for a planned method reports this rather than claiming the name does not exist.
Examples
cpt_methods()
Changepoint accuracy metrics
Description
Computes standard accuracy metrics comparing predicted changepoints to ground truth, including precision/recall/F1 with margin, covering metric, Hausdorff distance, adjusted Rand index, annotation error, and MAE/RMSE of matched locations.
Usage
cpt_metrics(pred, truth, n, margin = 5)
Arguments
pred |
Predicted changepoint indices (integer vector). |
truth |
Ground truth changepoint indices (integer vector). |
n |
Length of the series. |
margin |
Tolerance margin for matching (default 5). |
Details
Precision/recall use a one-to-one matching: each truth may be
claimed by at most one prediction (predictions are scanned in order and
take the earliest unmatched truth within margin, which yields a
maximum matching for interval-structured problems). When pred and
truth are both empty the segmentation is exactly right, so
precision, recall, and F1 are all 1. The covering metric follows
van den Burg and Williams (2020): the prediction-side partition is always
well defined, so an empty pred scores the covering of the trivial
single-segment partition rather than 0.
Value
A tibble with columns: n, n_pred, n_truth,
precision, recall, f1, covering,
hausdorff, rand_index, annotation_error,
mae_matched, rmse_matched.
Examples
cpt_metrics(c(100, 200), c(100, 200), n = 300)
cpt_metrics(c(101, 205), c(100, 200), n = 300, margin = 5)
Multi-annotator evaluation
Description
Computes averaged covering and F1 scores against multiple annotation sets, as used in the Turing Change Point Dataset benchmark.
Usage
cpt_metrics_annotated(pred, annotations, n, margin = 5)
Arguments
pred |
Predicted changepoint indices. |
annotations |
A list of ground-truth annotation vectors. |
n |
Length of the series. |
margin |
Tolerance margin (default 5). |
Value
A tibble with averaged metrics.
Construct changepoint penalties
Description
Helper to construct standard penalty values for use with changepoint detection methods. Returns a numeric penalty value.
Usage
cpt_penalty(type, n = NULL, k = 1, value = NULL, alpha = 1.01)
Arguments
type |
Penalty type: |
n |
Series length (at least 3 for the |
k |
Number of parameters per changepoint (typically 2 for
mean+variance, 1 for mean-only). Defaults to 1. The |
value |
Numeric value for |
alpha |
Exponent of the strengthened SIC ( |
Value
A numeric penalty value.
Penalty semantics across engines
The same penalty name may be interpreted differently by different engines:
-
changepoint-based methods (PELT, BinSeg, SegNeigh, AMOC): accept character penalties (
"MBIC","BIC","AIC","Hannan-Quinn","None") and pass them to the upstream changepoint package. A numeric penalty is translated to that package'spenalty = "Manual"pluspen.value. The one exception is Segment Neighbourhood, for which changepoint does not implement MBIC:cpt_detect(method = "segneigh")andcpt_wrapper(cp_method = "SegNeigh")therefore fall back to"SIC"when the default penalty is left in place, so a segneigh result is not directly penalty-comparable with a PELT one. Passpenaltyexplicitly to pin it. For a change in mean these engines also read the penalty on the data's own scale rather than a standardised one; see the scale-sensitivity section ofcpt_detect. -
Functional-pruning methods (
fpop,cpop,decafs): accept numeric penalties only. When a character penalty is supplied viacpt_detect(), it is resolved to a numeric value usingcpt_penalty()before dispatch. -
Search-based methods (WBS, WBS2, NOT, MOSUM, IDetect, TGUH): use internal model-selection criteria (e.g., sSIC, threshold) and generally ignore the
penaltyargument. Specify thresholds via the wrapper's own arguments. -
Inference/Bayesian methods (
smuce,bcp,bocpd,beast,cpm,sn): are tuned by a significance level, posterior-probability threshold, hazard, or average run length rather than a penalty; see each wrapper. -
MBICincpt_penalty()is a BIC-type penalty that adds a combinatorial term for the number of wayskchangepoints can be placed innobservations,0.5(k+1)\log n + \log{n \choose k}. It is deliberately stronger than"BIC". It is not the modified BIC of Zhang and Siegmund (2007), whose penalty1.5 k \log n + 0.5 \sum_i \log(l_i / n)depends on the segment lengthsl_iand so cannot be expressed by a function ofnandkalone. Use the character"MBIC"with changepoint-based methods to get the engine's native MBIC.
Examples
cpt_penalty("BIC", n = 100)
cpt_penalty("AIC", n = 100)
cpt_penalty("Manual", value = 5)
Generate simulated changepoint data
Description
Creates a synthetic time series with known changepoints for testing and benchmarking.
Usage
cpt_simulate(
n,
changepoints = integer(),
change_in = c("mean", "var", "meanvar", "slope"),
params = NULL,
noise = c("gauss", "t", "ar1", "rw"),
sd = 1,
df = 3,
rho = 0,
seed = NULL
)
rcpt(...)
Arguments
n |
Length of the series. |
changepoints |
Integer vector of changepoint locations (last index of each segment before the change). |
change_in |
What changes: |
params |
A list of parameters per segment. For |
noise |
Noise type: |
sd |
Noise standard deviation, non-negative (for Gaussian and t;
t-noise is rescaled so its standard deviation is exactly |
df |
Degrees of freedom for t-noise; must exceed 2 so the variance exists. Defaults to 3. |
rho |
AR(1) autocorrelation parameter, strictly between -1 and 1 for
stationarity. Defaults to 0. Used only when |
seed |
Optional seed for reproducibility. |
... |
Passed to |
Value
A tibble with columns index, value, and seg_id.
The true changepoints are stored in the true_changepoints attribute.
Examples
dat <- cpt_simulate(200, changepoints = c(100), change_in = "mean",
params = c(0, 10), seed = 2022)
attr(dat, "true_changepoints")
Changepoint stability diagnostics via bootstrap
Description
Most engines report a point set of changepoints with no measure of how
fragile it is. cpt_stability() fits the detector once, then
resamples residuals within the fitted segments (so the estimated
regime structure is preserved), re-runs the detector on each replicate,
and reports how often each location is re-detected. The resulting
detection-frequency profile is a cheap, model-agnostic confidence signal
available for every wrapped engine, including the many that ship no
confidence intervals.
Usage
cpt_stability(x, method = "pelt", B = 100, margin = 5, seed = NULL, ...)
## S3 method for class 'ggcpt_stability'
print(x, ...)
## S3 method for class 'ggcpt_stability'
autoplot(object, ...)
Arguments
x |
For |
method |
Detection method, passed to |
B |
Number of bootstrap replicates. Defaults to |
margin |
Tolerance (in indices) when counting a replicate detection
as a re-detection of a location. Defaults to |
seed |
Optional seed for reproducibility. |
... |
Additional arguments passed to every |
object |
A |
Value
A ggcpt_stability object: a list with frequency
(a tibble of index and freq, the proportion of replicates
detecting a changepoint within margin of that index),
original (the point-estimate ggcpt), and B.
Methods: print() and autoplot() (frequency profile with
the original detections marked).
Examples
set.seed(2026)
x <- c(rnorm(60), rnorm(60, 4))
st <- cpt_stability(x, method = "pelt", B = 20)
st
ggplot2::autoplot(st)
Changepoint wrapper
Description
This function wraps a number of cpt functions from the changepoint
package and the cpt.np() function from the changepoint.np package.
It is handy that users can use this function to get the same changepoint
results as these functions output individually. Moreover, it returns a tibble
that inherits the tidyverse style. Functions from the changepoint package do
require data normality assumption by default, yet changepoint.np is a
non-parametric way to detect changepoints and let data speak by itself.
If user sets change_in as np (or cpt_np), a seed should
be set before using the function for the sake of reproducibility. For more
details on the changepoint and changepoint.np packages, please refer to
their documentation.
Usage
cpt_wrapper(data, change_in = "mean_var", cp_method = "PELT", ...)
Arguments
data |
A numeric vector. |
change_in |
Choice of |
cp_method |
A wide range of choices (i.e., |
... |
Extra arguments for each |
Value
A tibble including which point(s) is/are the changepoint along with
raw changepoint value corresponding to that changepoint. Changepoint
locations follow the convention of the changepoint package: the
last index of the left segment. The upstream cpt object is
attached as the "ggcpt_fit" attribute, which is what
cpt_detect() stores in the result's $fit.
Standardise the data for a change in mean
With change_in = "mean" the upstream Normal cost assumes a noise
standard deviation of 1 and the penalty is compared against the raw
residual sum of squares, so a series with wider noise is under-penalised
and over-segmented: 29 changepoints instead of 1 at \sigma = 3 in a
measured example. Standardise the series first, or use
change_in = "mean_var", which estimates a variance per segment and
is unaffected. See the scale-sensitivity section of
cpt_detect.
References
Killick R, Eckley I (2014). “changepoint: An R package for changepoint analysis.” Journal of statistical software, 58(3), 1–19.
Examples
set.seed(2022)
cpt_wrapper(c(rnorm(100,0,1),rnorm(100,0,10)))
cpt_wrapper(c(rnorm(100,0,1),rnorm(100,10,1)))
DeCAFS wrapper — changes amid drift and autocorrelated noise
Description
Wraps DeCAFS::DeCAFS() (Romano, Rigaill, Runge and Fearnhead,
2022), which detects abrupt mean changes when the underlying signal also
drifts (random-walk fluctuations) and the noise is AR(1)-autocorrelated —
the two regimes in which plain change-in-mean methods over-detect. Model
parameters are estimated automatically unless supplied.
Usage
decafs_wrapper(x, penalty = NULL, model_param = NULL, ...)
Arguments
x |
A numeric vector. |
penalty |
Penalty |
model_param |
Optional list of model parameters
( |
... |
Additional arguments passed to |
Value
A ggcpt object. The data tibble carries the
estimated signal in its fitted column.
References
Romano G, Rigaill G, Runge V, Fearnhead P (2022). “Detecting abrupt changes in the presence of local fluctuations and autocorrelated noise.” Journal of the American Statistical Association, 117(540), 2147–2162.
Examples
set.seed(2026)
res <- decafs_wrapper(c(rnorm(100), rnorm(100, 5)))
res$changepoints
ecp wrapper
Description
The ecp package provides a non-parametric way to detect changepoints. Unlike
the changepoint package, it does not assume raw data to have any formal
distribution. This wrapper function wraps two functions from the ecp package,
i.e., e.divisive() and e.agglo(). Users can use either function
by switching the algorithm argument. Before using the wrapper function,
seed should be set for the sake of reproducibility.
Usage
ecp_wrapper(data, algorithm = "divisive", min_size = 2, seed = NULL, ...)
Arguments
data |
A numeric vector (for univariate) or matrix/data.frame (for multivariate). |
algorithm |
Either |
min_size |
Minimum number of observations between change points. By
default is 2. This argument is only applied when |
seed |
Optional. A seed for reproducibility of the stochastic permutation test. |
... |
Extra arguments to pass on either from |
Value
A tibble includes which point(s) is/are the changepoint along with
raw changepoint value corresponding to that changepoint. Changepoint
locations follow the ecp package convention: the first index of the
right segment. When no changepoint is found, an empty tibble is returned
(0 rows). The upstream fit is not retained — and $fit is
NULL on a ggcpt from cpt_detect(method = "ecp") —
because ecp::e.agglo()'s cluster-progression matrix is quadratic
in the series length; call the ecp functions directly if you need
their full output.
References
James NA, Matteson DS (2014). “ecp: An R package for nonparametric multiple change point analysis of multivariate data.” Journal of Statistical Software, 62(7), 1–25. doi:10.18637/jss.v062.i07.
Examples
set.seed(2022)
ecp_wrapper(c(rnorm(100,0,1),rnorm(100,0,10)))
ecp_wrapper(c(rnorm(100,0,1),rnorm(100,10,1)))
EnvCpt wrapper — changepoints versus trends versus autocorrelation
Description
Wraps EnvCpt::envcpt() (Beaulieu and Killick, 2018), which fits up
to twelve competing models — constant mean or linear trend, each with or
without changepoints, and with white-noise, AR(1) or AR(2) errors — and
lets an information criterion decide whether the series really contains
changepoints or merely trend/autocorrelation ("memory"). The changepoints
of the winning model (if any) are returned, and the winning model's name
is recorded, guarding against the classic false positive of running a
mean-shift detector on autocorrelated data.
Usage
envcpt_wrapper(
x,
models = c("mean", "meancpt", "meanar1", "meanar2", "meanar1cpt", "meanar2cpt",
"trend", "trendcpt", "trendar1", "trendar2", "trendar1cpt", "trendar2cpt"),
criterion = c("AIC", "BIC"),
minseglen = 5,
...
)
Arguments
x |
A numeric vector. |
models |
Character vector of models to fit; see
|
criterion |
Model selection criterion: |
minseglen |
Minimum segment length. Defaults to |
... |
Additional arguments passed to |
Value
A ggcpt object. $fit holds the full envcpt
output; the selected model name is stored in the penalty descriptor and
printed by glance() via penalty_type. Individual model
fits that fail are expected — the criterion ignores them — so the
engine's own try() output is not passed on; genuine warnings
still are, and a series on which no model fits at all raises an error.
References
Beaulieu C, Killick R (2018). “Distinguishing trends and shifts from memory in climate data.” Journal of Climate, 31(23), 9519–9543.
Examples
set.seed(2026)
res <- envcpt_wrapper(c(rnorm(100), rnorm(100, 3)))
res$changepoints
fastcpd wrapper — fast changepoint detection via sequential gradient descent
Description
Wraps the fastcpd package (Li and Zhang, 2024), a modern PELT-family engine that pairs pruning with sequential gradient descent so that exact or near-exact segmentations of many model families run in near-linear time. This wrapper exposes the time-series families most useful alongside the other engines: mean, variance, mean-and-variance, and AR/ARMA/GARCH model changepoints.
Usage
fastcpd_wrapper(
x,
family = c("mean", "variance", "meanvariance", "ar", "arma", "garch"),
order = NULL,
...
)
Arguments
x |
A numeric vector, or (for |
family |
Model family: |
order |
Model order for |
... |
Additional arguments passed to the corresponding
|
Value
A ggcpt object.
References
Li X, Zhang X (2024). “fastcpd: Fast change point detection in R.” arXiv preprint arXiv:2404.05933.
Examples
set.seed(2026)
res <- fastcpd_wrapper(c(rnorm(100), rnorm(100, 4)))
res$changepoints
FPOP wrapper — Functional Pruning Optimal Partitioning
Description
Wraps the fpop package for optimal changepoint detection via
functional pruning.
Usage
fpop_wrapper(x, penalty = NULL, ...)
Arguments
x |
A numeric vector. |
penalty |
Penalty value. Defaults to |
... |
Additional arguments passed to |
Value
A ggcpt object.
Changepoint vertical rules geom
Description
Draws vertical lines at changepoint locations. Mimics geom_vline
but designed to work with the tidy changepoint data frames returned by
the package. Can be used as a standalone layer:
geom_changepoint(data = cp_df, aes(xintercept = cp)).
Usage
geom_changepoint(
mapping = NULL,
data = NULL,
...,
na.rm = FALSE,
show.legend = NA
)
Arguments
mapping |
Set of aesthetic mappings created by |
data |
A data frame with changepoint information. |
... |
Other arguments passed to |
na.rm |
If |
show.legend |
Whether to show legend. |
Value
A ggplot layer.
Changepoint confidence interval geom
Description
Draws horizontal whiskers for changepoint-location confidence intervals (e.g. from MOSUM, stepR, strucchange, segmented).
Usage
geom_cpt_ci(mapping = NULL, data = NULL, ..., na.rm = FALSE, show.legend = NA)
Arguments
mapping |
Aesthetic mappings. Requires |
data |
A data frame with CI information. |
... |
Other arguments passed to |
na.rm |
If |
show.legend |
Whether to show legend. |
Value
A ggplot layer.
Changepoint segment level geom
Description
Draws horizontal segments representing the estimated level of each segment
between changepoints. Typically used with data from augment().
Usage
geom_cpt_segment(
mapping = NULL,
data = NULL,
...,
na.rm = FALSE,
show.legend = NA
)
Arguments
mapping |
Aesthetic mappings. Requires |
data |
A data frame with segment information. |
... |
Other arguments passed to |
na.rm |
If |
show.legend |
Whether to show legend. |
Value
A ggplot layer.
Geometrically-inspired multivariate changepoint wrapper (geomcp)
Description
Wraps changepoint.geo::geomcp() (Grundy, Killick and Mihaylov,
2020): each multivariate observation is mapped to its distance from, and
angle to, a reference point, and univariate PELT is run on the two mapped
series. Distance changes capture shifts in magnitude, angle changes
capture shifts in orientation/correlation structure.
Usage
geomcp_wrapper(
x,
penalty = "MBIC",
mapping = c("both", "distance", "angle"),
...
)
Arguments
x |
A numeric matrix or data frame with one row per time point. |
penalty |
Penalty for the univariate PELT runs (a
changepoint-style character penalty). Defaults to |
mapping |
Which mapped series' changepoints to report:
|
... |
Additional arguments passed to
|
Value
A ggcpt object whose changepoints tibble carries a
mapping column ("distance" or "angle"; a location
found in both is labelled "both").
References
Grundy T, Killick R, Mihaylov G (2020). “High-dimensional changepoint detection via a geometrically inspired mapping.” Statistics and Computing, 30, 1155–1166.
Examples
set.seed(2026)
X <- rbind(matrix(rnorm(100 * 4), 100), matrix(rnorm(100 * 4, 2), 100))
res <- geomcp_wrapper(X)
res$changepoints
Compare multiple changepoint detection methods
Description
Runs several detectors on the same data and returns a faceted or overlaid
ggplot comparison. Respects future::plan() for parallel execution
if the future.apply package is available.
Usage
ggcpt_compare(
x,
methods = c("pelt", "binseg", "amoc"),
layout = c("facet", "overlay"),
change_in = "mean",
seed = NULL,
...
)
Arguments
x |
A numeric vector (the data series). A one-column matrix or data
frame is accepted; wider input is refused, because these detectors are
univariate and flattening the columns would invent a changepoint at
every seam. Use |
methods |
Character vector of method names (passed to |
layout |
Layout type. |
change_in |
What to detect change in. Passed to each detector. |
seed |
Optional seed for reproducible parallelism. Passed to
|
... |
Additional arguments passed to each detector. |
Value
A ggplot object.
Examples
set.seed(2022)
x <- c(rnorm(100, 0, 1), rnorm(100, 10, 1))
ggcpt_compare(x, methods = c("pelt", "binseg"))
Comparison table
Description
Returns a tidy tibble combining the results of multiple detectors on the same series.
Usage
ggcpt_compare_table(
x,
methods = c("pelt", "binseg", "amoc"),
change_in = "mean",
...
)
Arguments
x |
A numeric vector (the data series). A one-column matrix or data
frame is accepted; wider input is refused, because these detectors are
univariate and flattening the columns would invent a changepoint at
every seam. Use |
methods |
Character vector of method names. |
change_in |
What to detect change in. |
... |
Additional arguments passed to each detector. |
Value
A tibble with columns method, cp, cp_value.
Evaluation visualization
Description
Overlays predictions and ground truth on the series with tolerance windows,
colouring true positives, false positives, and misses. Uses the same
one-to-one matching as cpt_metrics(), so the plot and the
metrics agree.
Usage
ggcpt_eval(pred, truth, data_vec, margin = 5)
Arguments
pred |
Predicted changepoint indices. |
truth |
Ground truth changepoint indices. |
data_vec |
The original data vector (for context). |
margin |
Tolerance margin (default 5). |
Value
A ggplot object.
Interactive changepoint plot
Description
Renders a ggcpt result (or any ggplot built from one) as an
interactive HTML widget via plotly, with values on hover. A thin
convenience wrapper: the static autoplot() path is untouched.
Usage
ggcpt_interactive(x, ...)
Arguments
x |
A |
... |
Additional arguments passed to |
Value
A plotly htmlwidget.
Examples
res <- cpt_detect(c(rnorm(50), rnorm(50, 5)), method = "pelt")
ggcpt_interactive(res)
Coerce, format, and plot ggcpt objects
Description
Convenience S3 methods for working with ggcpt objects: coerce the
changepoints to a tibble or data frame, render a one-line summary string, or
produce the default plot (a base-graphics fallback that delegates to
autoplot.ggcpt).
Usage
## S3 method for class 'ggcpt'
as_tibble(x, ..., .name_repair = NULL)
## S3 method for class 'ggcpt'
as.data.frame(x, row.names = NULL, optional = FALSE, ...)
## S3 method for class 'ggcpt'
format(x, ...)
## S3 method for class 'ggcpt'
plot(x, ...)
Arguments
x |
A |
... |
Additional arguments passed to methods. |
.name_repair |
Ignored (the changepoints tibble already has valid, unique names); present for signature compatibility with the generic. |
row.names, optional |
Passed to |
Value
as_tibble() and as.data.frame() return the changepoints
table; format() returns a length-one character string; plot()
returns a ggplot object.
Examples
set.seed(2022)
res <- cpt_detect(c(rnorm(50), rnorm(50, 5)), method = "pelt")
as_tibble(res)
as.data.frame(res)
format(res)
Posterior probability plot for Bayesian results
Description
Draws the classic Bayesian changepoint display: the series with its
posterior mean (top panel) and the per-location posterior probability of
a changepoint (bottom panel). Works with results from
bcp_wrapper() and beast_wrapper().
Usage
ggcpt_posterior(x, prob_threshold = NULL)
Arguments
x |
A |
prob_threshold |
Probability cutoff drawn as a horizontal reference line in the probability panel; defaults to the threshold recorded on the object (or 0.5). |
Value
A ggplot object (two facets sharing the x axis).
Examples
res <- bcp_wrapper(c(rnorm(60), rnorm(60, 4)), seed = 2026)
ggcpt_posterior(res)
Run-length posterior heatmap for Bayesian online results
Description
Draws the signature BOCPD graphic: the posterior distribution of the run
length (time since the last changepoint) at every observation, as a
heatmap, with the series overlaid on top. Works with results from
bocpd_wrapper().
Usage
ggcpt_runlength(x, prob_floor = 0.001)
Arguments
x |
A |
prob_floor |
Posterior probabilities below this value are not drawn
(keeps the heatmap legible). Defaults to |
Value
A ggplot object.
Examples
res <- bocpd_wrapper(c(rnorm(60), rnorm(60, 4)))
ggcpt_runlength(res)
Plot for the changepoint package
Description
The plot for changepoints detected by the changepoint package is a line plot for the raw data and the vertical lines representing each changepoint. The x-axis is the row number of the raw data in the original data vector. The plot inherits ggplot2, meaning users can add ggplot2 functions on top the changepoint plot for customization.
Usage
ggcptplot(
data,
change_in = "mean_var",
cp_method = "PELT",
...,
cptline_alpha = 1,
cptline_color = "blue",
cptline_type = "solid",
cptline_linewidth = 0.5,
cptline_size = lifecycle::deprecated(),
index = NULL,
show_points = NULL,
show_line = TRUE
)
Arguments
data |
A numeric vector. |
change_in |
Choice of |
cp_method |
A wide range of choices (i.e., |
... |
Extra arguments for each |
cptline_alpha |
The value of alpha for the vertical changepoint line(s), default is 1, meaning no transparency. |
cptline_color |
The color for the vertical changepoint line(s), default
is |
cptline_type |
The linetype for the vertical changepoint line(s),
default is |
cptline_linewidth |
The linewidth for the vertical changepoint line(s),
default is |
cptline_size |
Deprecated. Use |
index |
Optional. A vector of x-axis labels (e.g. dates) of the same
length as |
show_points |
Logical. Whether to draw data points. Defaults to
|
show_line |
Logical. Whether to draw the line. Defaults to |
Value
A line plot with data points along with the vertical lines representing changepoints.
Examples
ggcptplot(c(rnorm(100,0,1),rnorm(100,0,10)))
ggcptplot(c(rnorm(100,0,1),rnorm(100,10,1)))
Plot for the ecp package
Description
The plot for changepoints detected by the ecp package is a line plot for the raw data and the vertical lines representing each changepoint. The x-axis is the row number of the raw data in the original data vector. The plot inherits ggplot2, meaning users can add ggplot2 functions on top the changepoint plot for customization.
Usage
ggecpplot(
data,
algorithm = "divisive",
min_size = 2,
...,
cptline_alpha = 1,
cptline_color = "blue",
cptline_type = "solid",
cptline_linewidth = 0.5,
cptline_size = lifecycle::deprecated(),
index = NULL,
show_points = NULL,
show_line = TRUE
)
Arguments
data |
A numeric vector (for univariate) or matrix/data.frame (for multivariate). |
algorithm |
Either |
min_size |
Minimum number of observations between change points. By
default is 2. This argument is only applied when |
... |
Extra arguments to pass on either from |
cptline_alpha |
The value of alpha for the vertical changepoint line(s), default is 1, meaning no transparency. |
cptline_color |
The color for the vertical changepoint line(s), default
is |
cptline_type |
The linetype for the vertical changepoint line(s),
default is |
cptline_linewidth |
The linewidth for the vertical changepoint line(s),
default is |
cptline_size |
Deprecated. Use |
index |
Optional. A vector of x-axis labels (e.g. dates) of the same
length as |
show_points |
Logical. Whether to draw data points. Defaults to
|
show_line |
Logical. Whether to draw the line. Defaults to |
Value
A line plot with data points along with the vertical lines representing changepoints.
Examples
ggecpplot(c(rnorm(100,0,1),rnorm(100,0,10)))
ggecpplot(c(rnorm(100,0,1),rnorm(100,10,1)))
Glance at a ggcpt object
Description
Returns a one-row summary of a changepoint detection result.
Usage
## S3 method for class 'ggcpt'
glance(x, ...)
Arguments
x |
A |
... |
Additional arguments (ignored). |
Details
total_cost is reported on whatever scale the engine itself uses, so
it is meaningful when comparing penalties within one method and not when
comparing one method against another. For the changepoint engines it
is the unpenalised -2\log L of the chosen segmentation. Four cases
there are NA rather than filled with a number that would not mean
the same thing:
-
"binseg"and"segneigh", whosecpt.rangefits report the raw within-segment cost instead — for one and the same segmentation that is 219.7 where a PELT fit reports 659.9; -
"np", because changepoint.np defines nologLikmethod; a change in mean under the default
"MBIC"penalty. Loading changepoint.np — which this package imports, so it is always loaded — replaces changepoint'slogLikmethod forcptobjects with one that errors on exactly that combination. Any other penalty ("BIC","AIC", a numeric value) reports normally, as dochange_in = "var"and"meanvar".
Value
A one-row tibble with columns: n, n_changepoints,
method, change_in, penalty_type, penalty_value,
cp_convention, total_cost (NA when the engine does
not expose a cost), runtime (elapsed seconds when measured by
cpt_detect(), otherwise NA).
Isolate-Detect wrapper
Description
Wraps the IDetect package. Requires the IDetect package.
Usage
idetect_wrapper(x, seed = NULL, ...)
Arguments
x |
A numeric vector. |
seed |
Optional seed for reproducibility. |
... |
Additional arguments passed to |
Value
A ggcpt object. When the engine finds no changepoints
(including when it signals "No change-points found"), an empty result
is returned rather than an error. A constant series likewise returns the
empty result; see the note below.
Constant input
IDetect::ID() does not treat a flat series consistently — its
statistics become 0/0, and what comes back depends on the value and
the length. rep(3, 200) yields 126 changepoints, at
1, 3, 4, 6, 7, ...; rep(0, 100) raises "No change-points found";
rep(-2.5, 60) returns the sentinel 0. A constant series plainly has
no changepoint, and every other search wrapper here reports none, so this
one short-circuits to the empty result. Constancy is decided by exact
equality, so a series with tiny but genuine variation still reaches the
engine.
inspect wrapper — high-dimensional changepoints via sparse projection
Description
Wraps InspectChangepoint::inspect() (Wang and Samworth, 2018). For
a p-variate series whose mean changes in an unknown sparse subset of
coordinates, the algorithm computes the CUSUM transformation, finds the
optimal sparse projection direction via a convex relaxation, and locates
changepoints on the projected univariate series, recursing via wild binary
segmentation.
Usage
inspect_wrapper(x, lambda = NULL, threshold = NULL, ...)
Arguments
x |
A numeric matrix or data frame with one row per time point and one column per coordinate. |
lambda |
Regularisation parameter of the sparse projection; when
|
threshold |
Detection threshold; when |
... |
Additional arguments passed to
|
Value
A ggcpt object. The changepoints tibble carries a
strength column (the maximum projected CUSUM statistic). The
first coordinate is used for cp_value and the univariate plot
line; the full matrix is kept for the faceted multivariate
autoplot(). Coordinates that are constant carry no changepoint
information and would make the engine's variance rescaling undefined, so
they are dropped (with a warning) before detection and an all-constant
matrix returns an empty result; the dropped coordinates are still kept
for plotting, and reported locations always refer to the original rows.
References
Wang T, Samworth RJ (2018). “High dimensional change point estimation via sparse projection.” Journal of the Royal Statistical Society: Series B, 80(1), 57–83.
Examples
set.seed(2026)
X <- cbind(c(rnorm(80), rnorm(80, 3)), c(rnorm(80), rnorm(80, -2)),
rnorm(160))
res <- inspect_wrapper(X)
res$changepoints
Test if an object is a ggcpt object
Description
Test if an object is a ggcpt object
Usage
is_ggcpt(x)
Arguments
x |
An object to test. |
Value
TRUE if x inherits from ggcpt.
Kernel changepoint wrapper (KCP on running statistics)
Description
Wraps kcpRS::kcpRS() (Cabrieto et al., 2018; the KCP framework of
Arlot, Celisse and Harchaoui, 2019). The data are mapped to a running
statistic (mean, variance, autocorrelation, or correlation) computed on a
sliding window, and a Gaussian-kernel change point analysis with a
permutation significance test is run on the statistic. Detecting changes
in running correlations or variances captures higher-order changes that
mean-based methods miss. Multivariate input (matrix or data frame) is
supported.
Usage
kcp_wrapper(
x,
running_stat = c("mean", "var", "autocorr", "corr"),
wsize = 25,
nperm = 1000,
kmax = 10,
alpha = 0.05,
seed = NULL,
...
)
Arguments
x |
A numeric vector, matrix, or data frame (columns are variables). |
running_stat |
Which running statistic to monitor: |
wsize |
Sliding window size for the running statistic. Defaults to
|
nperm |
Number of permutations for the significance test, at least 2.
Defaults to |
kmax |
Maximum number of changepoints considered. Defaults to
|
alpha |
Significance level of the permutation test. Defaults to
|
seed |
Optional seed for reproducibility of the permutation test. |
... |
Additional arguments passed to |
Value
A ggcpt object. Reported locations refer to the centre of
the sliding window in which the change occurs. The series must be at
least wsize long to form one window. Constant coordinates make
every running statistic NA, so they are dropped (with a warning)
before detection and an all-constant input returns an empty result.
References
Arlot S, Celisse A, Harchaoui Z (2019). “A kernel multiple change-point algorithm via model selection.” Journal of Machine Learning Research, 20(162), 1–56.
Cabrieto J, Adolf J, Tuerlinckx F, Kuppens P, Ceulemans E (2018). “Detecting long-lived autodependency changes in a multivariate system via change point detection and regime switching models.” Scientific Reports, 8, 15637.
Examples
res <- kcp_wrapper(c(rnorm(60), rnorm(60, 3)), nperm = 100, seed = 2026)
res$changepoints
MOSUM wrapper — Moving Sum
Description
Wraps the mosum package for moving-sum-based changepoint
detection, either at a single bandwidth or (with
multiscale = TRUE) across a bandwidth grid with localised pruning.
Usage
mosum_wrapper(x, G = NULL, multiscale = FALSE, seed = NULL, ...)
Arguments
x |
A numeric vector. |
G |
Bandwidth. If |
multiscale |
Logical. Use the multiscale MOSUM procedure
( |
seed |
Optional seed for reproducibility. |
... |
Additional arguments passed to |
Value
A ggcpt object.
Create a ggcpt object
Description
Create a ggcpt object
Usage
new_ggcpt(
changepoints = tibble::tibble(cp = integer(), cp_value = numeric()),
segments = tibble::tibble(seg_id = integer(), start = integer(), end = integer(), n =
integer(), param_estimate = numeric()),
data = tibble::tibble(index = integer(), value = numeric()),
method = NA_character_,
change_in = NA_character_,
penalty = list(type = NA_character_, value = NA_real_),
fit = NULL,
call = NULL,
cp_convention = "left",
runtime = NA_real_
)
Arguments
changepoints |
A tibble with columns |
segments |
A tibble with segment information: |
data |
A tibble with |
method |
Character. The detection method used. A length-one string;
defaults to |
change_in |
Character. What was detected (e.g. "mean", "var",
"meanvar"). A length-one string; defaults to |
penalty |
A list with |
fit |
The raw upstream object. Every wrapper stores one except
|
call |
The matched call. |
cp_convention |
Character. The convention for reporting changepoint
locations: |
runtime |
Numeric. Elapsed detection time in seconds, if measured.
Defaults to |
Value
An object of class ggcpt.
NOT wrapper — Narrowest-Over-Threshold
Description
Wraps the not package for changepoint detection via the
Narrowest-Over-Threshold method. The contrast determines what change is
detected: piecewise-constant mean (default), mean and variance, or
(continuous or discontinuous) piecewise-linear trend.
Usage
not_wrapper(x, contrast = "pcwsConstMean", seed = NULL, ...)
Arguments
x |
A numeric vector. |
contrast |
Contrast type. One of |
seed |
Optional seed for reproducibility. |
... |
Additional arguments passed to |
Value
A ggcpt object whose change_in reflects the
contrast: "mean", "meanvar", or "slope".
Nonparametric MOSUM wrapper (NP-MOJO)
Description
Wraps CptNonPar::np.mojo() (McGonigle and Cho, 2025): nonparametric
moving-sum detection of changes in the marginal or joint distribution of a
(possibly multivariate) time series, robust to serial dependence.
Usage
npmojo_wrapper(x, G = NULL, lag = 0, ...)
Arguments
x |
A numeric vector or matrix (rows are time points). |
G |
Moving-window bandwidth. Defaults to |
lag |
Time lag at which changes in the joint distribution are
examined; |
... |
Additional arguments passed to |
Value
A ggcpt object. Constant coordinates leave the kernel
statistics undefined, so they are dropped (with a warning) before
detection and an all-constant input returns an empty result. The
engine calibrates its detection threshold by bootstrap, so the value
recorded in the penalty descriptor varies between runs; call
set.seed() beforehand, or pass threshold = "manual" and
threshold.val through ..., for a reproducible one.
References
McGonigle ET, Cho H (2025). “Nonparametric data segmentation in multivariate time series via joint characteristic functions.” Biometrika, 112(2), asaf024.
Examples
res <- npmojo_wrapper(c(rnorm(100), rnorm(100, 3)))
res$changepoints
ocd wrapper — online high-dimensional changepoint detection
Description
Wraps the ocd package (Chen, Wang and Samworth, 2022): online
multiscale detection of a mean change in a high-dimensional stream, with
worst-case detection-delay guarantees and per-observation cost independent
of history. The detector assumes standardised data with known pre-change
mean; this wrapper estimates the baseline mean and standard deviation
from an initial training window, then monitors the remainder of the
series, resetting after each declaration so multiple changes can be
found.
Usage
ocd_wrapper(
x,
train = NULL,
thresh = "MC",
patience = 5000,
beta = 1,
mc_reps = 100,
...
)
Arguments
x |
A numeric matrix or data frame with one row per time point and at
least two columns. The |
train |
Number of initial observations used to estimate the baseline
mean/sd (not monitored). Defaults to
|
thresh |
Threshold specification passed to
|
patience |
Target average run length to false alarm. Defaults to
|
beta |
Assumed lower bound on the squared Euclidean norm of the mean
change. Defaults to |
mc_reps |
Monte Carlo repetitions for threshold calibration.
Defaults to |
... |
Additional arguments passed to
|
Value
A ggcpt object. Because the detector is online, reported
locations are declaration times (the changepoint plus the
detection delay), stored together with a declared_at column.
How long this takes
Nearly all of the run time is ocd's Monte Carlo threshold
calibration, which happens before a single observation is read. It is
linear in mc_reps and grows with the number of coordinates:
measured at mc_reps = 5, construction takes about 3 s at
p = 3, 9 s at p = 10 and 55 s at p = 50, and four
times as long at mc_reps = 20. At the default mc_reps = 100
that extrapolates to roughly a minute at p = 3 and a quarter of an
hour at p = 50. Monitoring the observations afterwards is cheap by
comparison — well under a second for a thousand of them. Lower
mc_reps while exploring, or pass thresh directly to skip
calibration entirely.
References
Chen Y, Wang T, Samworth RJ (2022). “High-dimensional, multiscale online changepoint detection.” Journal of the Royal Statistical Society: Series B, 84(1), 234–266.
Examples
set.seed(2026)
X <- rbind(matrix(rnorm(60 * 3), 60), matrix(rnorm(40 * 3, 3), 40))
res <- ocd_wrapper(X, mc_reps = 5)
res$changepoints
Print a ggcpt object
Description
Print a ggcpt object
Usage
## S3 method for class 'ggcpt'
print(x, ...)
Arguments
x |
A |
... |
Additional arguments (ignored). |
Objects exported from other packages
Description
These objects are imported from other packages. Follow the links below to see their documentation.
Broken-line regression wrapper (segmented)
Description
Wraps segmented::segmented() (Muggeo, 2003, 2008): maximum
likelihood estimation of continuous piecewise-linear
("broken-line") regressions, with standard errors and confidence
intervals for the breakpoint locations. Where the step-change engines
model jumps in the level, segmented models kinks in the trend, so
change_in is "slope" and the fitted broken line is stored in
the fitted column for autoplot(show_fit = TRUE).
Usage
segmented_wrapper(x, npsi = 1, conf_level = 0.95, seed = NULL, ...)
Arguments
x |
A numeric vector; a linear model of |
npsi |
Number of breakpoints to estimate. Defaults to |
conf_level |
Confidence level for breakpoint intervals. Defaults to
|
seed |
Optional seed (the estimator uses bootstrap restarting). |
... |
Additional arguments passed to |
Value
A ggcpt object with ci_lower/ci_upper columns
and the fitted broken line in $data$fitted. Breakpoints are
rounded to the nearest index; for a continuous fit the reported location
is the kink itself. A constant series has no kink and returns an empty
result, rather than the arbitrary breakpoint a singular fit would give.
References
Muggeo VM (2003). “Estimating regression models with unknown break-points.” Statistics in Medicine, 22(19), 3055–3071.
Muggeo VM (2008). “segmented: An R package to fit regression models with broken-line relationships.” R News, 8(1), 20–25.
Examples
set.seed(2026)
y <- cumsum(c(rep(0.5, 100), rep(-0.3, 100))) + rnorm(200)
res <- segmented_wrapper(y, npsi = 1)
res$changepoints
ggplot2::autoplot(res, show_fit = TRUE, show_ci = TRUE)
Blocks test signal
Description
The classic Donoho-Johnstone blocks test signal with known changepoints.
Usage
signal_blocks(n = 2048, seed = NULL)
Arguments
n |
Length of the signal. Defaults to 2048. |
seed |
Optional seed. |
Value
A tibble with columns index and value. The true_changepoints
attribute contains the known changepoint locations.
References
Donoho, D. L. and Johnstone, I. M. (1994). Ideal spatial adaptation by wavelet shrinkage. Biometrika, 81(3), 425-455.
FMS (Four-Metric-Segments) test signal
Description
A piecewise-constant test signal from the WBS/NOT literature.
Usage
signal_fms(n = 2000, seed = NULL)
Arguments
n |
Length of the signal. Defaults to 2000. |
seed |
Optional seed. |
Value
A tibble with columns index and value.
Mix test signal
Description
A piecewise-constant/linear signal from the literature.
Usage
signal_mix(n = 2000, seed = NULL)
Arguments
n |
Length of the signal. Defaults to 2000. |
seed |
Optional seed. |
Value
A tibble with columns index and value.
Stairs test signal
Description
A monotonically stepping signal (staircase).
Usage
signal_stairs(n = 2000, seed = NULL)
Arguments
n |
Length of the signal. Defaults to 2000. |
seed |
Optional seed. |
Value
A tibble with columns index and value.
Teeth test signal
Description
A piecewise-constant signal with regularly spaced changepoints.
Usage
signal_teeth(n = 2000, seed = NULL)
Arguments
n |
Length of the signal. Defaults to 2000. |
seed |
Optional seed. |
Value
A tibble with columns index and value.
SMUCE / HSMUCE wrapper — multiscale changepoint inference
Description
Wraps stepR::stepFit() for the Simultaneous MUltiscale Changepoint
Estimator (SMUCE) of Frick, Munk and Sieling (2014) and its heterogeneous
extension HSMUCE (Pein, Sieling and Munk, 2017). SMUCE estimates a step
function subject to a simultaneous multiscale test at level alpha;
the level bounds the probability of over-estimating the number of
changepoints, and the fit delivers confidence intervals for every
changepoint location, which populate the ci_lower/ci_upper
columns of the result and render via autoplot(show_ci = TRUE) or
geom_cpt_ci().
Usage
smuce_wrapper(x, alpha = 0.5, family = c("gauss", "hsmuce"), ...)
Arguments
x |
A numeric vector. |
alpha |
Significance level of the multiscale test in |
family |
Noise model: |
... |
Additional arguments passed to |
Value
A ggcpt object. The changepoints tibble carries
ci_lower/ci_upper (confidence interval for each
changepoint location) and the data tibble carries the SMUCE step
fit in its fitted column.
References
Frick K, Munk A, Sieling H (2014). “Multiscale change point inference.” Journal of the Royal Statistical Society: Series B, 76(3), 495–580.
Pein F, Sieling H, Munk A (2017). “Heterogeneous change point inference.” Journal of the Royal Statistical Society: Series B, 79(4), 1207–1227.
Examples
set.seed(2026)
x <- c(rnorm(100), rnorm(100, 3))
res <- smuce_wrapper(x)
res$changepoints
ggplot2::autoplot(res, show_ci = TRUE)
Self-normalisation wrapper (SNSeg)
Description
Wraps SNSeg::SNSeg_Uni() (Zhao, Jiang and Shao, 2022):
self-normalised segmentation with nested local windows. Self-normalisation
avoids estimating the long-run variance, is robust to temporal dependence,
and detects changes in general parameters — mean, variance, quantiles,
autocorrelation, or bivariate correlation — within one framework.
Usage
sn_wrapper(
x,
parameter = c("mean", "variance", "acf", "bivcor"),
confidence = 0.9,
grid_size = NULL,
...
)
Arguments
x |
A numeric vector (or a two-column matrix for
|
parameter |
Which parameter to test for changes: |
confidence |
Confidence level of the self-normalised test, one of
0.9, 0.95, 0.99, 0.995 or 0.999. Defaults to |
grid_size |
Grid size controlling the local-window sweep; when
|
... |
Additional arguments passed to |
Value
A ggcpt object. About 20 observations are needed for the
nested local windows at the default grid_size; a constant series
returns an empty result rather than an engine error.
References
Zhao Z, Jiang F, Shao X (2022). “Segmenting time series via self-normalisation.” Journal of the Royal Statistical Society: Series B, 84(5), 1699–1725.
Examples
set.seed(2026)
res <- sn_wrapper(c(rnorm(150), rnorm(150, 3)))
res$changepoints
Changepoint detection stat
Description
Runs changepoint detection inside the ggplot pipeline. Useful for
quick exploration: ggplot(df, aes(t, y)) + geom_line() +
stat_changepoint(method = "pelt"). Draws vertical lines at detected
changepoint locations.
Usage
stat_changepoint(
mapping = NULL,
data = NULL,
geom = "vline",
position = "identity",
...,
method = "pelt",
change_in = "mean",
na.rm = FALSE,
show.legend = NA
)
Arguments
mapping |
Aesthetic mappings. |
data |
A data frame. |
geom |
The geometric object to use (default: |
position |
Position adjustment. |
... |
Other arguments passed to the geom. |
method |
Detection method (passed to |
change_in |
What to detect change in (passed to |
na.rm |
If |
show.legend |
Whether to show legend. |
Value
A ggplot layer.
Bai-Perron structural break wrapper (strucchange)
Description
Wraps strucchange::breakpoints() (Zeileis et al., 2002), the
dynamic-programming implementation of the Bai and Perron (1998, 2003)
multiple structural break estimator. Called with a bare numeric vector it
dates mean shifts (y ~ 1); called with a formula and data it dates
breaks in arbitrary regression coefficients. Break-date confidence
intervals from confint() populate ci_lower/ci_upper
and render via autoplot(show_ci = TRUE).
Usage
strucchange_wrapper(
x,
data = NULL,
breaks = NULL,
h = 0.15,
conf_level = 0.95,
...
)
Arguments
x |
A numeric vector (mean-shift mode), or a model formula
(regression mode; supply |
data |
Optional data frame for formula input. |
breaks |
Maximum number of breaks; when |
h |
Minimal segment size, as a fraction of the sample size (or an
integer count). Defaults to |
conf_level |
Confidence level for the break-date intervals. Defaults
to |
... |
Additional arguments passed to
|
Value
A ggcpt object with ci_lower/ci_upper columns
on the changepoints tibble.
Result size
$fit is the breakpoints object itself, and that object is
quadratic in the series length: it keeps RSS.triang, the triangular
table of segment residual sums of squares, which is what lets
strucchange return the optimal segmentation for any number
of breaks without refitting. Measured here, the whole result is about
1.7 MB at n = 200, 5.9 MB at n = 400 and 22.6 MB at
n = 800 — roughly four times larger each time the series doubles —
and that one table outweighs everything else in the fit put together, by a
margin that widens as the series grows. A single fit is not a problem; a
few hundred of them are, so when running this engine over a panel with
cpt_batch() keep what you need
(res$changepoints) rather than the whole list of results. No other
engine here behaves this way: the median result across the other thirty is
under ten times the size of the series it was given.
References
Bai J, Perron P (2003). “Computation and analysis of multiple structural change models.” Journal of Applied Econometrics, 18(1), 1–22.
Zeileis A, Leisch F, Hornik K, Kleiber C (2002). “strucchange: An R package for testing for structural change in linear regression models.” Journal of Statistical Software, 7(2), 1–38.
Examples
set.seed(2026)
res <- strucchange_wrapper(c(rnorm(100), rnorm(100, 3)))
res$changepoints
Summary of a ggcpt object
Description
Provides a human-readable digest of a changepoint detection result, including the segment table with levels and lengths, total cost, penalty, and runtime.
Usage
## S3 method for class 'ggcpt'
summary(object, ...)
## S3 method for class 'summary.ggcpt'
print(x, ...)
Arguments
object |
A |
... |
Additional arguments (ignored). |
x |
A |
Value
A list with class summary.ggcpt containing the summary.
TGUH wrapper
Description
Wraps the breakfast package for Tail-Greedy Unbalanced-Haar
detection, with information-criterion model selection.
Usage
tguh_wrapper(x, ...)
Arguments
x |
A numeric vector. |
... |
Additional arguments passed to |
Value
A ggcpt object.
ggchangepoint theme
Description
A minimal, publication-ready ggplot2 theme for changepoint plots.
Usage
theme_ggcpt(base_size = 11, base_family = "")
Arguments
base_size |
Base font size. Defaults to 11. |
base_family |
Base font family. Defaults to "". |
Value
A ggplot2 theme object.
Examples
library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + geom_point() + theme_ggcpt()
Tidy a ggcpt object
Description
Returns the changepoints tibble (one row per changepoint).
Usage
## S3 method for class 'ggcpt'
tidy(x, ...)
Arguments
x |
A |
... |
Additional arguments (ignored). |
Value
A tibble with columns cp, cp_value, and any
method-specific columns.
WBS2 wrapper — Wild Binary Segmentation 2
Description
Wraps the breakfast package's WBS2 solution path with
steepest-drop-to-low-levels (SDLL) model selection.
Usage
wbs2_wrapper(x, ...)
Arguments
x |
A numeric vector. |
... |
Additional arguments passed to |
Value
A ggcpt object.
WBS wrapper — Wild Binary Segmentation
Description
Wraps the wbs package for randomised changepoint detection via
Wild Binary Segmentation.
Usage
wbs_wrapper(x, n_intervals = 5000, threshold = NULL, seed = NULL, ...)
Arguments
x |
A numeric vector. |
n_intervals |
Number of random intervals. Defaults to |
threshold |
Manual threshold for detection. If |
seed |
Optional seed for reproducibility. |
... |
Additional arguments passed to |
Value
A ggcpt object.