% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/lmforest.R
\name{lmforest}
\alias{lmforest}
\title{Create Forest Plot for Linear Models}
\usage{
lmforest(
  x,
  data = NULL,
  title = "Linear Model",
  effect_label = "Coefficient",
  digits = 2,
  p_digits = 3,
  conf_level = 0.95,
  font_size = 1,
  annot_size = 3.88,
  header_size = 5.82,
  title_size = 23.28,
  plot_width = NULL,
  plot_height = NULL,
  table_width = 0.6,
  show_n = TRUE,
  indent_groups = FALSE,
  condense_table = FALSE,
  bold_variables = FALSE,
  center_padding = 4,
  zebra_stripes = TRUE,
  ref_label = "reference",
  labels = NULL,
  units = "in",
  color = "#5A8F5A",
  qc_footer = TRUE,
  number_format = NULL
)
}
\arguments{
\item{x}{Either a fitted linear model object (class \code{lm} or \code{lmerMod}), 
a \code{fit_result} object from \code{fit()}, or a \code{fullfit_result}
object from \code{fullfit()}. When a \code{fit_result} or \code{fullfit_result}
is provided, the model, data, and labels are automatically extracted.}

\item{data}{Data frame or data.table containing the original data used to 
fit the model. If \code{NULL} (default) and \code{x} is a model, the function 
attempts to extract data from the model object. If \code{x} is a \code{fit_result},
data is extracted automatically. Providing data explicitly is recommended when
passing a model directly.}

\item{title}{Character string specifying the plot title displayed at the top. 
Default is \code{"Linear Model"}.}

\item{effect_label}{Character string for the effect measure label on the 
forest plot axis. Default is \code{"Coefficient"}.}

\item{digits}{Integer specifying the number of decimal places for coefficients 
and confidence intervals. Default is 2.}

\item{p_digits}{Integer specifying the number of decimal places for
\emph{p}-values. Values smaller than \code{10^(-p_digits)} are displayed
as \code{"< 0.001"} (for \code{p_digits = 3}), \code{"< 0.0001"} (for
\code{p_digits = 4}), etc. Default is 3.}

\item{conf_level}{Numeric confidence level for confidence intervals. Must be
between 0 and 1. Default is 0.95 (95\% confidence intervals). The CI
percentage is automatically displayed in column headers (\emph{e.g.,} "90\% CI"
when \code{conf_level = 0.90}).}

\item{font_size}{Numeric multiplier controlling the base font size for all 
text elements. Default is 1.0.}

\item{annot_size}{Numeric value controlling the relative font size for data 
annotations. Default is 3.88.}

\item{header_size}{Numeric value controlling the relative font size for column 
headers. Default is 5.82.}

\item{title_size}{Numeric value controlling the relative font size for the 
main plot title. Default is 23.28.}

\item{plot_width}{Numeric value specifying the intended output width in 
specified \code{units}. Default is \code{NULL} (automatic).}

\item{plot_height}{Numeric value specifying the intended output height in 
specified \code{units}. Default is \code{NULL} (automatic).}

\item{table_width}{Numeric value between 0 and 1 specifying the proportion of 
total plot width allocated to the data table. Default is 0.6.}

\item{show_n}{Logical. If \code{TRUE}, includes a column showing group-specific 
sample sizes.
Counts describe the observations used in fitting rather than every row
supplied. Default is \code{TRUE}.}

\item{indent_groups}{Logical. If \code{TRUE}, indents factor levels under 
their parent variable name, creating hierarchical structure. The "Group" 
column is hidden when \code{TRUE}. Default is \code{FALSE}.}

\item{condense_table}{Logical. If \code{TRUE}, condenses binary categorical 
variables into single rows. Automatically sets \code{indent_groups = TRUE}. 
Default is \code{FALSE}.}

\item{bold_variables}{Logical. If \code{TRUE}, variable names are displayed
in bold. If \code{FALSE} (default), variable names are displayed in plain
text.}

\item{center_padding}{Numeric value specifying horizontal spacing between 
table and forest plot. Default is 4.}

\item{zebra_stripes}{Logical. If \code{TRUE}, applies alternating gray 
background shading to different variables. Default is \code{TRUE}.}

\item{ref_label}{Character string to display for reference categories of 
factor variables. Default is \code{"reference"}.}

\item{labels}{Named character vector providing custom display labels for 
variables. Example: \code{c(age = "Age (years)", height = "Height (cm)")}. 
Default is \code{NULL}, in which case the labels attached by the function
that produced \code{x} are used, where \code{x} is a \pkg{summata} result
rather than a model object. Original variable names are used where neither
is available.}

\item{units}{Character string specifying units for plot dimensions: 
\code{"in"} (inches), \code{"cm"}, or \code{"mm"}. Default is \code{"in"}.}

\item{color}{Character string specifying the color for coefficient point 
estimates in the forest plot. Default is \code{"#5A8F5A"} (green). Use 
hex codes or R color names.}

\item{qc_footer}{Logical. If \code{TRUE}, displays model quality control
statistics in the footer (observations analyzed, \emph{R}\eqn{^2}, adjusted
\emph{R}\eqn{^2}, \emph{F}-statistic, AIC). Default is \code{TRUE}.}

\item{number_format}{Character string or two-element character vector
  controlling thousand and decimal separators in formatted output. Named
  presets:
  \itemize{
    \item \code{"us"} - Comma thousands, period decimal: \code{1,234.56} [default]
    \item \code{"eu"} - Period thousands, comma decimal: \code{1.234,56}
    \item \code{"space"} - Thin-space thousands, period decimal: \code{1 234.56}
      (SI/ISO 31-0)
    \item \code{"none"} - No thousands separator: \code{1234.56}
  }
  Or provide a custom two-element vector \code{c(big.mark, decimal.mark)},
  \emph{e.g.}, \code{c("'", ".")} for Swiss-style: \verb{1'234.56}.

  When \code{NULL} (default), uses
  \code{getOption("summata.number_format", "us")}. Set the global option
  once per session to avoid passing this argument repeatedly:
  \preformatted{
    options(summata.number_format = "eu")
  }}
}
\value{
A \code{ggplot} object containing the complete forest plot. The plot 
  can be:
  \itemize{
    \item Displayed directly: \code{print(plot)}
    \item Saved to file: \code{forestsave(plot, "forest.pdf")}
    \item Further customized with \pkg{ggplot2} functions
  }
  
  The returned object includes an attribute \code{"rec_dims"} 
  accessible via \code{attr(plot, "rec_dims")}, which is a list 
  containing:
  \describe{
    \item{width}{Numeric. Recommended plot width in specified units}
    \item{height}{Numeric. Recommended plot height in specified units}
  }
  
  These recommendations are automatically calculated based on the number of 
  variables, text sizes, and layout parameters, and are printed to console 
  if \code{plot_width} or \code{plot_height} are not specified. The list also 
  carries a \code{units} element recording the units the dimensions are 
  expressed in, matching the \code{units} argument. \code{forestsave()} reads 
  all three and requires no further handling.

  The returned object also includes an attribute \code{"table_data"}
  accessible via \code{attr(plot, "table_data")}, a data.table holding the
  values drawn in the plot: one row per term in model order, with the
  variable, factor level, sample size, estimate, confidence bounds and
  p-value. Sample sizes describe the observations used in fitting rather
  than every row supplied, so they sum to the model sample size within each
  variable.
}
\description{
Generates a publication-ready forest plot that combines a formatted data table 
with a graphical representation of regression coefficients from a linear model. 
The plot integrates variable names, group levels, sample sizes, coefficients 
with confidence intervals, \emph{p}-values, and model diagnostics (\emph{R}\eqn{^2},
\emph{F}-statistic, AIC) in a single comprehensive visualization designed for
manuscripts and presentations.
}
\details{
\strong{Linear Model-Specific Features:}

The linear model forest plot differs from logistic and Cox plots in several ways:
\itemize{
  \item \strong{Coefficients}: Raw regression coefficients shown (not exponentiated)
  \item \strong{Reference line}: At coefficient = 0 (not at 1)
  \item \strong{Linear scale}: Forest plot uses linear scale (not log scale)
  \item \strong{No events column}: Only sample sizes shown (no event counts)
  \item \strong{\emph{R}\eqn{^2} statistics}: Model fit assessed by \emph{R}\eqn{^2} and adjusted \emph{R}\eqn{^2}
  \item \strong{\emph{F}-test}: Overall model significance from \emph{F}-statistic
}

\strong{Plot Components:}

\enumerate{
  \item \strong{Title}: Centered at top
  \item \strong{Data Table} (left): Contains:
    \itemize{
      \item Variable: Predictor names
      \item Group: Factor levels (if applicable)
      \item \emph{n}: Sample sizes by group
      \item Coefficient (95\% CI); \emph{p}-value: Raw coefficients with CIs and \emph{p}-values
    }
  \item \strong{Forest Plot} (right):
    \itemize{
      \item Point estimates (squares sized by sample size)
      \item 95\% confidence intervals (error bars)
      \item Reference line at coefficient = 0
      \item Linear scale
    }
  \item \strong{Model Statistics} (footer):
    \itemize{
      \item Observations analyzed (with total observations and percentage)
      \item \emph{R}\eqn{^2} and adjusted \emph{R}\eqn{^2}
      \item \emph{F}-statistic with degrees of freedom and \emph{p}-value
      \item AIC
    }
}

\strong{Interpreting Coefficients:}

Linear regression coefficients represent the change in the outcome variable 
for a one-unit change in the predictor:
\itemize{
  \item \strong{Continuous predictors}: Coefficient = change in Y per unit of X
  \item \strong{Binary predictors}: Coefficient = difference in Y between groups
  \item \strong{Factor predictors}: Coefficients = differences from reference 
    category
  \item \strong{Sign matters}: Positive = increase in Y, Negative = decrease in Y
  \item \strong{Zero crossing}: CI crossing zero suggests no significant effect
}

Example: If the coefficient for "age" is 0.50 when predicting BMI, 
BMI increases by 0.50 kg/m\eqn{^2} for each additional year of age.

\strong{Model Fit Statistics:}

The footer displays key diagnostics:
\itemize{
  \item \strong{\emph{R}\eqn{^2}}: Proportion of variance explained (0 to 1)
    \itemize{
      \item 0.0-0.3: Weak explanatory power
      \item 0.3-0.5: Moderate
      \item 0.5-0.7: Good
      \item > 0.7: Strong (rare in social/biological sciences)
    }
  \item \strong{Adjusted \emph{R}\eqn{^2}}: \emph{R}\eqn{^2} penalized for number of predictors
    \itemize{
      \item Always \eqn{\le} \emph{R}\eqn{^2}
      \item Preferred for model comparison
      \item Accounts for model complexity
    }
  \item \strong{\emph{F}-statistic}: Tests null hypothesis that all coefficients = 0
    \itemize{
      \item Degrees of freedom: df1 = # predictors, df2 = # observations - # predictors - 1
      \item Significant \emph{p}-value indicates model explains variance better than intercept-only
    }
  \item \strong{AIC}: For model comparison (lower is better)
}

\strong{Assumptions:}

Linear regression assumes:
\enumerate{
  \item Linearity of relationships
  \item Independence of observations
  \item Homoscedasticity (constant variance)
  \item Normality of residuals
  \item No multicollinearity
}

Check assumptions using:
\itemize{
  \item \code{plot(model)} for diagnostic plots
  \item \code{car::vif(model)} for multicollinearity
  \item \code{lmtest::bptest(model)} for heteroscedasticity
  \item \code{shapiro.test(residuals(model))} for normality
}

\strong{Reference Categories:}

For factor variables:
\itemize{
  \item First level is the reference (coefficient = 0)
  \item Other levels show difference from reference
  \item Reference displayed with \code{ref_label}
  \item Relevel factors before modeling if needed: 
    \code{factor(x, levels = c("desired_ref", ...))}
}

\strong{Sample Size Reporting:}

The "\emph{n}" column shows:
\itemize{
  \item For continuous variables: Total observations with non-missing data
  \item For factor variables: Number of observations in each category
  \item Footer shows observations used in fitting, the total supplied, and 
    the percentage retained (accounting for missing values)
}
}
\examples{
data(clintrial)
data(clintrial_labels)

# Create example model
model1 <- lm(bmi ~ age + sex + smoking, data = clintrial)

# Example 1: Basic linear model forest plot
p <- lmforest(model1, data = clintrial)

\donttest{

old_width <- options(width = 180)

# Example 2: With custom labels and title
plot2 <- lmforest(
    x = model1,
    data = clintrial,
    title = "Predictors of Body Mass Index",
    effect_label = "Change in BMI (kg/m^2)",
    labels = clintrial_labels
)

# Example 3: Comprehensive model with indented layout
model3 <- lm(
    bmi ~ age + sex + smoking + hypertension + diabetes + creatinine,
    data = clintrial
)

plot3 <- lmforest(
    x = model3,
    data = clintrial,
    labels = clintrial_labels,
    indent_groups = TRUE,
    zebra_stripes = TRUE
)

# Example 4: Condensed layout
plot4 <- lmforest(
    x = model3,
    data = clintrial,
    condense_table = TRUE,
    labels = clintrial_labels
)

# Example 5: Different outcome (hemoglobin)
model5 <- lm(
    hemoglobin ~ age + sex + bmi + smoking + creatinine,
    data = clintrial
)

plot5 <- lmforest(
    x = model5,
    data = clintrial,
    title = "Predictors of Baseline Hemoglobin",
    effect_label = "Change in Hemoglobin (g/dL)",
    labels = clintrial_labels
)

# Example 6: Save with recommended dimensions
forestsave(plot5, file.path(tempdir(), "linear_forest.pdf"))

options(old_width)

}
}
\seealso{
\code{\link{autoforest}} for automatic model detection,
\code{\link{glmforest}} for logistic/GLM forest plots,
\code{\link{coxforest}} for Cox model forest plots,
\code{\link{uniforest}} for univariable screening forest plots,
\code{\link{multiforest}} for multi-outcome forest plots,
\code{\link[stats]{lm}} for fitting linear models,
\code{\link{fit}} for regression modeling,
  \code{\link{forestsave}} for saving with recommended dimensions

Other visualization functions:
\code{\link[=autoforest]{autoforest()}},
\code{\link[=coxforest]{coxforest()}},
\code{\link[=forestsave]{forestsave()}},
\code{\link[=glmforest]{glmforest()}},
\code{\link[=multiforest]{multiforest()}},
\code{\link[=recdims]{recdims()}},
\code{\link[=uniforest]{uniforest()}}
}
\concept{visualization functions}
