% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/plot.R, R/tinyplot.R, R/visualisation_recipe.R
\name{plot.estimate_predicted}
\alias{plot.estimate_predicted}
\alias{plot.estimate_means}
\alias{tinyplot.estimate_means}
\alias{visualisation_recipe.estimate_predicted}
\alias{visualisation_recipe.estimate_slopes}
\alias{visualisation_recipe.estimate_grouplevel}
\title{Automated plotting for 'modelbased' objects}
\usage{
\method{plot}{estimate_predicted}(x, ...)

\method{plot}{estimate_means}(x, ...)

\method{tinyplot}{estimate_means}(
  x,
  type = NULL,
  dodge = NULL,
  show_data = FALSE,
  collapse_group = NULL,
  numeric_as_discrete = NULL,
  ...
)

\method{visualisation_recipe}{estimate_predicted}(
  x,
  show_data = FALSE,
  show_residuals = FALSE,
  collapse_group = NULL,
  point = NULL,
  line = NULL,
  pointrange = NULL,
  ribbon = NULL,
  facet = NULL,
  grid = NULL,
  join_dots = NULL,
  numeric_as_discrete = NULL,
  ...
)

\method{visualisation_recipe}{estimate_slopes}(
  x,
  line = NULL,
  pointrange = NULL,
  ribbon = NULL,
  facet = NULL,
  grid = NULL,
  ...
)

\method{visualisation_recipe}{estimate_grouplevel}(
  x,
  line = NULL,
  pointrange = NULL,
  ribbon = NULL,
  facet = NULL,
  grid = NULL,
  ...
)
}
\arguments{
\item{x}{A modelbased object.}

\item{...}{Arguments passed from \code{plot()} to \code{visualisation_recipe()}, or
to \code{tinyplot()} if you use that method.}

\item{type}{The type of \code{tinyplot} visualization. It is recommended that
users leave as \code{NULL} (the default), in which case the plot type will be
determined automatically by the underlying \code{modelbased} object.}

\item{dodge}{Dodge value for grouped plots. If \code{NULL} (the default), then
the dodging behavior is determined by the number of groups and
\code{getOption("modelbased_tinyplot_dodge")}.}

\item{show_data}{Logical, if \code{TRUE}, display the "raw" data as a background
to the model-based estimation. For mixed models, you can additionally use the
\code{collapse_group} argument to "collapse" data points by random effects
grouping factors. Argument \code{show_data} will be ignored for plotting objects
returned by \code{estimate_slopes()} or \code{estimate_grouplevel()}.}

\item{collapse_group}{This argument only takes effect when either \code{show_data}
or \code{show_residuals} is \code{TRUE}. For mixed effects models, name of the grouping
variable of random effects. If \code{collapse_group = TRUE}, data points
"collapsed" by the first random effect groups are added to the plot. Else, if
\code{collapse_group} is a name of a group factor, data is collapsed by that
specific random effect. See \code{\link[=collapse_by_group]{collapse_by_group()}} for further details.}

\item{numeric_as_discrete}{Maximum number of unique values in a numeric
predictor to treat that predictor as discrete. Defaults to \code{8}. Numeric
predictors are usually mapped to a continuous color scale, unless they have
only few unique values. In the latter case, numeric predictors are assumed to
represent "categories", e.g. when only the mean value and +/- 1 standard
deviation around the mean are chosen as representative values for that
predictor. Use \code{FALSE} to always use continuous color scales for numeric
predictors. It is possible to set a global default value using \code{options()},
e.g. \code{options(modelbased_numeric_as_discrete = 10)}.}

\item{show_residuals}{Logical, if \code{TRUE}, display residuals of the model as a
background to the model-based estimation. Residuals will be computed for the
predictors in the data grid, using \code{\link[=residualize_over_grid]{residualize_over_grid()}}. For mixed
models, you can additionally use the \code{collapse_group} argument to "collapse"
data points from residuals by random effects grouping factors.}

\item{point, line, pointrange, ribbon, facet, grid}{Additional
aesthetics and parameters for the geoms (see customization example).}

\item{join_dots}{Logical, if \code{TRUE} and for categorical focal terms in \code{by},
dots (estimates) are connected by lines, i.e. plots will be a combination of
dots with error bars and connecting lines. If \code{FALSE} (default), only dots
and error bars are shown. It is possible to set a global default value using
\code{options()}, e.g. \code{options(modelbased_join_dots = TRUE)}.}
}
\value{
An object of class \code{visualisation_recipe} that describes the layers
used to create a plot based on \code{{ggplot2}}. The related \code{plot()} method is in
the \code{{see}} package.
}
\description{
Most \strong{modelbased} objects can be visualized using either the \code{plot()}
function, which internally calls the \code{visualisation_recipe()} function and
relies on \code{{ggplot2}}. There is also a \code{tinyplot()} method, which uses the
\code{{tinyplot}} package and relies on the core R graphic system. See the
examples below for more information and examples on how to create and
customize plots.

The plotting works by mapping any predictors from the \code{by} argument to the
x-axis, colors, alpha (transparency) and facets. Thus, the appearance of the
plot depends on the order of the variables that you specify in the \code{by}
argument. For instance, the plots corresponding to
\code{estimate_relation(model, by=c("Species", "Sepal.Length"))} and
\code{estimate_relation(model, by=c("Sepal.Length", "Species"))} will look
different.

The automated plotting is primarily meant for convenient visual checks, but
for publication-ready figures, we recommend re-creating the figures using the
\code{{ggplot2}} package directly.
}
\details{
There are two options to remove the confidence bands or errors bars
from the plot. To remove error bars, simply set the \code{pointrange} geom to
\code{point}, e.g. \code{plot(..., pointrange = list(geom = "point"))}. To remove the
confidence bands from line geoms, use \code{ribbon = "none"}.
}
\section{Global Options to Customize Plots}{

Some arguments for \code{plot()} can get global defaults using \code{options()}:
\itemize{
\item \code{modelbased_join_dots}: \verb{options(modelbased_join_dots = <logical>)} will
set a default value for the \code{join_dots}.
\item \code{modelbased_numeric_as_discrete}: \verb{options(modelbased_numeric_as_discrete = <number>)}
will set a default value for the \code{modelbased_numeric_as_discrete} argument.
Can also be \code{FALSE}.
\item \code{modelbased_ribbon_alpha}: \verb{options(modelbased_ribbon_alpha = <number>)}
will set a default value for the \code{alpha} argument of the \code{ribbon} geom.
Should be a number between \code{0} and \code{1}.
\item \code{modelbased_tinyplot_dodge}: \verb{options(modelbased_tinyplot_dodge = <number>)}
will set a default value for the \code{dodge} argument (spacing between geoms)
when using \code{tinyplot::plt()}. Should be a number between \code{0} and \code{1}.
}
}

\examples{
\dontshow{if (all(insight::check_if_installed(c("tinyplot", "marginaleffects"), quietly = TRUE))) withAutoprint(\{ # examplesIf}
# ==============================================
# tinyplot
# ==============================================
\donttest{
library(tinyplot)
data(efc, package = "modelbased")
efc <- datawizard::to_factor(efc, c("e16sex", "c172code", "e42dep"))
m <- lm(neg_c_7 ~ e16sex + c172code + barthtot, data = efc)

em <- estimate_means(m, "c172code")
plt(em)

# pass additional tinyplot arguments for customization, e.g.
plt(em, theme = "classic")
plt(em, theme = "classic", flip = TRUE)
# etc.

# Aside: use tinyplot::tinytheme() to set a persistent theme
tinytheme("classic")

# continuous variable example
em <- estimate_means(m, "barthtot")
plt(em)

# grouped example
m <- lm(neg_c_7 ~ e16sex * c172code + e42dep, data = efc)
em <- estimate_means(m, c("e16sex", "c172code"))
plt(em)

# use plt_add (alias tinyplot_add) to add layers
plt_add(type = "l", lty = 2)

# Reset to default theme
tinytheme()
}
\dontshow{\}) # examplesIf}
\dontshow{if (all(insight::check_if_installed(c("marginaleffects", "see", "ggplot2", "lme4"), quietly = TRUE)) && getRversion() >= "4.1.0") withAutoprint(\{ # examplesIf}
library(ggplot2)
library(see)
# ==============================================
# estimate_relation, estimate_expectation, ...
# ==============================================
# Simple Model ---------------
x <- estimate_relation(lm(mpg ~ wt, data = mtcars))
layers <- visualisation_recipe(x)
layers
plot(layers)

# visualization_recipe() is called implicitly when you call plot()
plot(estimate_relation(lm(mpg ~ qsec, data = mtcars)))

\dontrun{
# It can be used in a pipe workflow
lm(mpg ~ qsec, data = mtcars) |>
  estimate_relation(ci = c(0.5, 0.8, 0.9)) |>
  plot()

# Customize aesthetics ----------

plot(x,
  point = list(color = "red", alpha = 0.6, size = 3),
  line = list(color = "blue", size = 3),
  ribbon = list(fill = "green", alpha = 0.7)
) +
  theme_minimal() +
  labs(title = "Relationship between MPG and WT")

# Customize raw data -------------

plot(x, point = list(geom = "density_2d_filled"), line = list(color = "white")) +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
  theme(legend.position = "none")

# Single predictors examples -----------

plot(estimate_relation(lm(Sepal.Length ~ Species, data = iris)))

# 2-ways interaction ------------

# Numeric * numeric
x <- estimate_relation(lm(mpg ~ wt * qsec, data = mtcars))
plot(x)

# Numeric * factor
x <- estimate_relation(lm(Sepal.Width ~ Sepal.Length * Species, data = iris))
plot(x)

# ==============================================
# estimate_means
# ==============================================
# Simple Model ---------------
x <- estimate_means(lm(Sepal.Width ~ Species, data = iris), by = "Species")
layers <- visualisation_recipe(x)
layers
plot(layers)

# Customize aesthetics
layers <- visualisation_recipe(x,
  point = list(width = 0.03, color = "red"),
  pointrange = list(size = 2, linewidth = 2),
  line = list(linetype = "dashed", color = "blue")
)
plot(layers)

# Two levels ---------------
data <- mtcars
data$cyl <- as.factor(data$cyl)

model <- lm(mpg ~ cyl * wt, data = data)

x <- estimate_means(model, by = c("cyl", "wt"))
plot(x)

# GLMs ---------------------
data <- data.frame(vs = mtcars$vs, cyl = as.factor(mtcars$cyl))
x <- estimate_means(glm(vs ~ cyl, data = data, family = "binomial"), by = c("cyl"))
plot(x)

# ==============================================
# Adding original data to the plot
# ==============================================
data(efc, package = "modelbased")
efc$e15relat <- as.factor(efc$e15relat)
efc$c161sex <- as.factor(efc$c161sex)
levels(efc$c161sex) <- c("male", "female")
model <- lme4::lmer(neg_c_7 ~ c161sex + (1 | e15relat), data = efc)

me <- estimate_means(model, "c161sex")
plot(me, show_data = TRUE)

# data points: collapse by / average over random effects groups -------
plot(me, show_data = TRUE, collapse_group = "e15relat")
}
\dontshow{\}) # examplesIf}
\dontshow{if (all(insight::check_if_installed(c("marginaleffects", "see", "ggplot2"), quietly = TRUE))) withAutoprint(\{ # examplesIf}
# ==============================================
# estimate_slopes
# ==============================================
model <- lm(Sepal.Width ~ Species * Petal.Length, data = iris)
x <- estimate_slopes(model, trend = "Petal.Length", by = "Species")

layers <- visualisation_recipe(x)
layers
plot(layers)

\dontrun{
# Customize aesthetics and add horizontal line and theme
layers <- visualisation_recipe(x, pointrange = list(size = 2, linewidth = 2))
plot(layers) +
  geom_hline(yintercept = 0, linetype = "dashed", color = "red") +
  theme_minimal() +
  labs(y = "Effect of Petal.Length", title = "Marginal Effects")

model <- lm(Petal.Length ~ poly(Sepal.Width, 4), data = iris)
x <- estimate_slopes(model, trend = "Sepal.Width", by = "Sepal.Width", length = 20)
plot(visualisation_recipe(x))

model <- lm(Petal.Length ~ Species * poly(Sepal.Width, 3), data = iris)
x <- estimate_slopes(model, trend = "Sepal.Width", by = c("Sepal.Width", "Species"))
plot(visualisation_recipe(x))
}
\dontshow{\}) # examplesIf}
\dontshow{if (all(insight::check_if_installed(c("ggplot2", "marginaleffects", "see", "lme4"), quietly = TRUE))) withAutoprint(\{ # examplesIf}
# ==============================================
# estimate_grouplevel
# ==============================================
\dontrun{
data <- lme4::sleepstudy
data <- rbind(data, data)
data$Newfactor <- rep(c("A", "B", "C", "D"))

# 1 random intercept
model <- lme4::lmer(Reaction ~ Days + (1 | Subject), data = data)
x <- estimate_grouplevel(model)
layers <- visualisation_recipe(x)
layers
plot(layers)

# 2 random intercepts
model <- lme4::lmer(Reaction ~ Days + (1 | Subject) + (1 | Newfactor), data = data)
x <- estimate_grouplevel(model)
plot(x) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  theme_minimal()
# Note: we need to use hline instead of vline because the axes is flipped

model <- lme4::lmer(Reaction ~ Days + (1 + Days | Subject) + (1 | Newfactor), data = data)
x <- estimate_grouplevel(model)
plot(x)
}
\dontshow{\}) # examplesIf}
}
