% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/mcmc-traces.R
\name{MCMC-traces}
\alias{MCMC-traces}
\alias{mcmc_trace}
\alias{mcmc_trace_highlight}
\alias{trace_style_np}
\alias{mcmc_rank_overlay}
\alias{mcmc_rank_hist}
\alias{mcmc_trace_data}
\title{Trace plots of MCMC draws}
\usage{
mcmc_trace(
  x,
  pars = character(),
  regex_pars = character(),
  transformations = list(),
  ...,
  facet_args = list(),
  n_warmup = 0,
  iter1 = 0,
  window = NULL,
  size = NULL,
  np = NULL,
  np_style = trace_style_np(),
  divergences = NULL
)

mcmc_trace_highlight(
  x,
  pars = character(),
  regex_pars = character(),
  transformations = list(),
  ...,
  facet_args = list(),
  n_warmup = 0,
  window = NULL,
  size = NULL,
  alpha = 0.2,
  highlight = 1
)

trace_style_np(div_color = "red", div_size = 0.25, div_alpha = 1)

mcmc_rank_overlay(
  x,
  pars = character(),
  regex_pars = character(),
  transformations = list(),
  ...,
  n_bins = 20,
  ref_line = FALSE
)

mcmc_rank_hist(
  x,
  pars = character(),
  regex_pars = character(),
  transformations = list(),
  ...,
  facet_args = list(),
  n_bins = 20,
  ref_line = FALSE
)

mcmc_trace_data(
  x,
  pars = character(),
  regex_pars = character(),
  transformations = list(),
  ...,
  highlight = NULL,
  n_warmup = 0,
  iter1 = 0
)
}
\arguments{
\item{x}{A 3-D array, matrix, list of matrices, or data frame of MCMC draws.
The \link{MCMC-overview} page provides details on how to specify each these
allowed inputs. It is also possible to use an object with an
\code{as.array()} method that returns the same kind of 3-D array described on
the \link{MCMC-overview} page.}

\item{pars}{An optional character vector of parameter names. If neither
\code{pars} nor \code{regex_pars} is specified then the default is to use \emph{all}
parameters. As of version \verb{1.7.0}, \strong{bayesplot} also supports 'tidy'
parameter selection by specifying \code{pars = vars(...)}, where \code{...} is
specified the same way as in \link[dplyr:select]{dplyr::select(...)} and
similar functions. Examples of using \code{pars} in this way can be found on the
\link[=tidy-params]{Tidy parameter selection} page.}

\item{regex_pars}{An optional \link[base:grep]{regular expression} to use for
parameter selection. Can be specified instead of \code{pars} or in addition to
\code{pars}. When using \code{pars} for tidy parameter selection, the \code{regex_pars}
argument is ignored since \link[tidyselect:select_helpers]{select helpers}
perform a similar function.}

\item{transformations}{Optionally, transformations to apply to parameters
before plotting. If \code{transformations} is a function or a single string
naming a function then that function will be used to transform all
parameters. To apply transformations to particular parameters, the
\code{transformations} argument can be a named list with length equal to
the number of parameters to be transformed. Currently only univariate
transformations of scalar parameters can be specified (multivariate
transformations will be implemented in a future release). If
\code{transformations} is a list, the name of each list element should be a
parameter name and the content of each list element should be a function
(or any item to match as a function via \code{\link[=match.fun]{match.fun()}}, e.g. a
string naming a function). If a function is specified by its name as a
string (e.g. \code{"log"}), then it can be used to construct a new
parameter label for the appropriate parameter (e.g. \code{"log(sigma)"}).
If a function itself is specified
(e.g. \code{log} or \code{function(x) log(x)})
then \code{"t"} is used in the new parameter label to indicate that the
parameter is transformed (e.g. \code{"t(sigma)"}).

Note: due to partial argument matching \code{transformations} can be
abbreviated for convenience in interactive use (e.g., \code{transform}).}

\item{...}{Currently ignored.}

\item{facet_args}{A named list of arguments (other than \code{facets}) passed
to \code{\link[ggplot2:facet_wrap]{ggplot2::facet_wrap()}} or \code{\link[ggplot2:facet_grid]{ggplot2::facet_grid()}}
to control faceting.}

\item{n_warmup}{An integer; the number of warmup iterations included in
\code{x}. The default is \code{n_warmup = 0}, i.e. to assume no warmup
iterations are included. If \code{n_warmup > 0} then the background for
iterations \code{1:n_warmup} is shaded gray.}

\item{iter1}{An integer; the iteration number of the first included draw
(default is \code{0}). This can be used to make it more obvious that the warmup
iterations have been discarded from the traceplot. It cannot be specified
if \code{n_warmup} is also set to a positive value.}

\item{window}{An integer vector of length two specifying the limits of a
range of iterations to display.}

\item{size}{An optional value to override the default line size
for \code{mcmc_trace()} or the default point size for \code{mcmc_trace_highlight()}.}

\item{np}{For models fit using \link{NUTS} (more generally, any
\href{https://en.wikipedia.org/wiki/Symplectic_integrator}{symplectic integrator}),
an optional data frame providing NUTS diagnostic information. The data
frame should be the object returned by \code{\link[=nuts_params]{nuts_params()}} or one with the same
structure. If \code{np} is specified then tick marks are added to the bottom of
the trace plot indicating within which iterations there was a divergence
(if there were any). See the end of the \strong{Examples} section, below.}

\item{np_style}{A call to the \code{trace_style_np()} helper function to
specify arguments controlling the appearance of tick marks representing
divergences (if the \code{np} argument is specified).}

\item{divergences}{Deprecated. Use the \code{np} argument instead.}

\item{alpha}{For \code{mcmc_trace_highlight()}, passed to
\code{\link[ggplot2:geom_point]{ggplot2::geom_point()}} to control the transparency of the points
for the chains not highlighted.}

\item{highlight}{For \code{mcmc_trace_highlight()}, an integer specifying one
of the chains that will be more visible than the others in the plot.}

\item{div_color, div_size, div_alpha}{Optional arguments to the
\code{trace_style_np()} helper function that are eventually passed to
\code{\link[ggplot2:geom_rug]{ggplot2::geom_rug()}} if the \code{np} argument is also specified. They control
the color, size, and transparency specifications for showing divergences in
the plot. The default values are displayed in the \strong{Usage} section above.}

\item{n_bins}{For the rank plots, the number of bins to use for the histogram
of rank-normalized MCMC samples. Defaults to \code{20}.}

\item{ref_line}{For the rank plots, whether to draw a horizontal line at the
average number of ranks per bin. Defaults to \code{FALSE}.}
}
\value{
The plotting functions return a ggplot object that can be further
customized using the \strong{ggplot2} package. The functions with suffix
\verb{_data()} return the data that would have been drawn by the plotting
function.

\code{mcmc_trace_data()} returns the data for the trace \emph{and} rank plots
in the same data frame.
}
\description{
Trace plot (or traceplot) of MCMC draws. See the \strong{Plot Descriptions}
section, below, for details.
}
\section{Plot Descriptions}{

\describe{
\item{\code{mcmc_trace()}}{
Standard trace plots of MCMC draws. For models fit using \link{NUTS},
the \code{np} argument can be used to also show divergences on the trace plot.
}
\item{\code{mcmc_trace_highlight()}}{
Traces are plotted using points rather than lines and the opacity of all
chains but one (specified by the \code{highlight} argument) is reduced.
}
\item{\code{mcmc_rank_hist()}}{
Whereas traditional trace plots visualize how the chains mix over the
course of sampling, rank histograms visualize how the values
from the chains mix together in terms of ranking. An ideal plot would
show the rankings mixing or overlapping in a uniform distribution.
See Vehtari et al. (2019) for details.
}
\item{\code{mcmc_rank_overlay()}}{
Ranks from \code{mcmc_rank_hist()} are plotted using overlaid lines in a
single panel.
}
}
}

\examples{
# some parameter draws to use for demonstration
x <- example_mcmc_draws(chains = 4, params = 6)
dim(x)
dimnames(x)

# trace plots of the betas
color_scheme_set("viridis")
mcmc_trace(x, regex_pars = "beta")
\donttest{
color_scheme_set("viridisA")
mcmc_trace(x, regex_pars = "beta")

color_scheme_set("viridisC")
mcmc_trace(x, regex_pars = "beta")
}

# mix color schemes
color_scheme_set("mix-blue-red")
mcmc_trace(x, regex_pars = "beta")

# use traditional ggplot discrete color scale
mcmc_trace(x, pars = c("alpha", "sigma")) +
 ggplot2::scale_color_discrete()

# zoom in on a window of iterations, increase line size,
# add tick marks, move legend to the top, add gray background
color_scheme_set("viridisA")
mcmc_trace(x[,, 1:4], window = c(100, 130), size = 1) +
  panel_bg(fill = "gray90", color = NA) +
  legend_move("top")

# Rank-normalized histogram plots. Instead of showing how chains mix over
# time, look at how the ranking of MCMC samples mixed between chains.
color_scheme_set("viridisE")
mcmc_rank_hist(x, "alpha")
mcmc_rank_hist(x, pars = c("alpha", "sigma"), ref_line = TRUE)
mcmc_rank_overlay(x, "alpha")

\dontrun{
# parse facet label text
color_scheme_set("purple")
p <- mcmc_trace(
  x,
  regex_pars = "beta\\\[[1,3]\\\]",
  facet_args = list(labeller = ggplot2::label_parsed)
)
p + facet_text(size = 15)

# mark first 100 draws as warmup
mcmc_trace(x, n_warmup = 100)

# plot as points, highlighting chain 2
color_scheme_set("brightblue")
mcmc_trace_highlight(x, pars = "sigma", highlight = 2, size = 2)

# for models fit using HMC/NUTS divergences can be displayed in the trace plot
library("rstanarm")
fit <- stan_glm(mpg ~ ., data = mtcars, refresh = 0,
  # next line to keep example fast and also ensure we get some divergences
                prior = hs(), iter = 400, adapt_delta = 0.8)

# extract draws using as.array (instead of as.matrix) to keep
# chains separate for trace plot
posterior <- as.array(fit)

# for stanfit and stanreg objects use nuts_params() to get the divergences
mcmc_trace(posterior, pars = "sigma", np = nuts_params(fit))

color_scheme_set("viridis")
mcmc_trace(
  posterior,
  pars = c("wt", "sigma"),
  size = 0.5,
  facet_args = list(nrow = 2),
  np = nuts_params(fit),
  np_style = trace_style_np(div_color = "black", div_size = 0.5)
)
}

}
\references{
Vehtari, A., Gelman, A., Simpson, D., Carpenter, B., Bürkner, P.
(2019). Rank-normalization, folding, and localization: An improved \emph{R}-hat
for assessing convergence of MCMC. \href{https://arxiv.org/abs/1903.08008}{arXiv preprint}.
}
\seealso{
Other MCMC: 
\code{\link{MCMC-combos}},
\code{\link{MCMC-diagnostics}},
\code{\link{MCMC-distributions}},
\code{\link{MCMC-intervals}},
\code{\link{MCMC-nuts}},
\code{\link{MCMC-overview}},
\code{\link{MCMC-parcoord}},
\code{\link{MCMC-recover}},
\code{\link{MCMC-scatterplots}}
}
\concept{MCMC}
