% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/glmforest.R
\name{glmforest}
\alias{glmforest}
\title{Create Forest Plot for Generalized Linear Models}
\usage{
glmforest(
  x,
  data = NULL,
  title = "Generalized Linear Model",
  effect_label = NULL,
  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,
  show_events = TRUE,
  indent_groups = FALSE,
  condense_table = FALSE,
  bold_variables = FALSE,
  center_padding = 4,
  zebra_stripes = TRUE,
  ref_label = "reference",
  labels = NULL,
  color = NULL,
  exponentiate = NULL,
  qc_footer = TRUE,
  units = "in",
  number_format = NULL
)
}
\arguments{
\item{x}{Either a fitted GLM object (class \code{glm} or \code{glmerMod}), 
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{"Generalized Linear Model"}. Use descriptive titles like 
"Risk Factors for Disease Outcome" for publication.}

\item{effect_label}{Character string for the effect measure label on the 
forest plot axis. If \code{NULL} (default), automatically determined based 
on model family and link function: "Odds Ratio" for logistic regression 
(\code{family = binomial, link = logit}), "Risk Ratio" for log-link models, 
"Exp(Coefficient)" for other exponential families, or "Coefficient" for 
identity link.}

\item{digits}{Integer specifying the number of decimal places for effect 
estimates and confidence intervals in the data table. 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. Values > 1 increase all fonts proportionally, values < 1 
decrease them. Default is 1.0. Useful for adjusting readability across 
different output sizes.}

\item{annot_size}{Numeric value controlling the relative font size for 
data annotations (variable names, values in table cells). Default is 3.88. 
Adjust relative to \code{font_size}.}

\item{header_size}{Numeric value controlling the relative font size for 
column headers ("Variable", "Group", "n", \emph{etc.}). Default is 5.82. Headers 
are typically larger than annotations for hierarchy.}

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

\item{plot_width}{Numeric value specifying the intended output width in 
specified \code{units}. Used for optimizing layout and text sizing. 
Default is \code{NULL} (automatic). Recommended: 10-16 inches for standard 
publications.}

\item{plot_height}{Numeric value specifying the intended output height in 
specified \code{units}. Default is \code{NULL} (automatic based on number 
of rows). The function provides recommendations if not specified.}

\item{table_width}{Numeric value between 0 and 1 specifying the proportion of 
total plot width allocated to the data table (left side). The forest plot 
occupies \code{1 - table_width}. Default is 0.6 (60\% table, 40\% forest). 
Increase for longer variable names, decrease to emphasize the forest plot.}

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

\item{show_events}{Logical. If \code{TRUE}, includes a column showing the 
number of events for each group. Relevant for logistic regression (number 
of cases) and other binary outcomes. Default is \code{TRUE}.}

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

\item{condense_table}{Logical. If \code{TRUE}, condenses binary categorical 
variables into single rows by showing only the non-reference category. 
Automatically sets \code{indent_groups = TRUE}. Useful for tables with 
many binary variables. 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 the horizontal spacing (in 
character units) between the data table and forest plot. Increase for more 
separation, decrease to fit more content. Default is 4.}

\item{zebra_stripes}{Logical. If \code{TRUE}, applies alternating gray 
background shading to different variables (not rows) to improve visual 
grouping and readability. Default is \code{TRUE}.}

\item{ref_label}{Character string to display for reference categories of 
factor variables. Typically shown in place of effect estimates. 
Default is \code{"reference"}. Common alternatives: "ref", "1.00 (ref)".}

\item{labels}{Named character vector or list providing custom display 
labels for variables. Names should match variable names in the model, 
values are the labels to display. Example: 
\code{c(age = "Age (years)", bmi = "Body Mass Index")}. 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{color}{Character string specifying the color for effect estimate point 
  markers in the forest plot. Use hex codes or R color names. Default is 
  \code{NULL}, which auto-selects based on effect type: \code{"#4BA6B6"} 
  (teal) for odds ratios (binomial/quasibinomial with logit link), 
  \code{"#3F87EE"} (blue) for rate/risk ratios (Poisson, Gamma, inverse 

  Gaussian with log link), and \code{"#5A8F5A"} (green) for coefficients 
  (Gaussian/identity link). This scheme matches \code{uniforest()} and 
  \code{multiforest()}. Choose colors that contrast well with black error bars.}

\item{exponentiate}{Logical. If \code{TRUE}, exponentiates coefficients to 
display odds ratios, risk ratios, \emph{etc.} If \code{FALSE}, shows raw 
coefficients. Default is \code{NULL}, which automatically exponentiates 
for logit, log, and cloglog links, and shows raw coefficients for identity 
link.}

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

\item{units}{Character string specifying the units for plot dimensions. 
Options: \code{"in"} (inches), \code{"cm"} (centimeters), \code{"mm"} 
(millimeters). Default is \code{"in"}. Affects interpretation of 
\code{plot_width} and \code{plot_height}.}

\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, event count, estimate, confidence
  bounds and p-value. Sample sizes and event counts 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 effect estimates (odds ratios, risk ratios, 
or coefficients) from a generalized linear model. The plot integrates variable 
names, group levels, sample sizes, effect estimates with confidence intervals, 
\emph{p}-values, and model diagnostics in a single comprehensive visualization designed 
for manuscripts and presentations.
}
\details{
\strong{Plot Components:}

The forest plot consists of several integrated components:
\enumerate{
  \item \strong{Title}: Centered at top, describes the analysis
  \item \strong{Data Table} (left side): Contains columns for:
    \itemize{
      \item Variable: Predictor names (or custom labels)
      \item Group: Factor levels (optional, hidden when indenting)
      \item n: Sample sizes by group (optional)
      \item Events: Event counts by group (optional)
      \item Effect (95\% CI); \emph{p}-value: Formatted estimates with \emph{p}-values
    }
  \item \strong{Forest Plot} (right side): Graphical display with:
    \itemize{
      \item Point estimates (squares sized by sample size)
      \item 95\% confidence intervals (error bars)
      \item Reference line (at OR/RR = 1 or coefficient = 0)
      \item Log scale for odds/risk ratios
      \item Labeled axis
    }
  \item \strong{Model Statistics} (footer): Summary of:
    \itemize{
      \item Observations analyzed (with total observations and percentage)
      \item Model family (Binomial, Poisson, \emph{etc.})
      \item Deviance statistics
      \item Pseudo-\emph{R}\eqn{^2} (McFadden)
      \item AIC
    }
}

\strong{Automatic Effect Measure Selection:}

When \code{effect_label = NULL} and \code{exponentiate = NULL}, the function 
intelligently selects the appropriate effect measure:
\itemize{
  \item \strong{Logistic regression} (\code{family = binomial(link = "logit")}): 
    Odds Ratios (OR)
  \item \strong{Log-link models} (\code{link = "log"}): Risk Ratios (RR) 
    or Rate Ratios
  \item \strong{Other exponential families}: exp(coefficient)
  \item \strong{Identity link}: Raw coefficients
}

\strong{Reference Categories:}

For factor variables, the first level (determined by factor ordering or 
alphabetically for character variables) serves as the reference category:
\itemize{
  \item Displayed with the \code{ref_label} instead of an estimate
  \item No confidence interval or \emph{p}-value shown
  \item Visually aligned with other categories
  \item When \code{condense_table = TRUE}, reference-only variables may be 
    omitted entirely
}

\strong{Layout Optimization:}

The function automatically optimizes layout based on content:
\itemize{
  \item Calculates appropriate axis ranges to accommodate all confidence intervals
  \item Selects meaningful tick marks on log or linear scales
  \item Sizes point markers proportional to sample size (larger = more data)
  \item Adjusts table width based on variable name lengths when \code{table_width = NULL}
  \item Recommends overall dimensions based on number of rows
}

\strong{Visual Grouping Options:}

Three display modes are available:
\enumerate{
  \item \strong{Standard} (\code{indent_groups = FALSE}, 
    \code{condense_table = FALSE}): 
    Separate "Variable" and "Group" columns, all categories shown
  \item \strong{Indented} (\code{indent_groups = TRUE}, 
    \code{condense_table = FALSE}): 
    Hierarchical display with groups indented under variables
  \item \strong{Condensed} (\code{condense_table = TRUE}): 
    Binary variables shown in single rows, automatically indented
}

\strong{Zebra Striping:}

When \code{zebra_stripes = TRUE}, alternating variables (not individual rows) 
receive light gray backgrounds. This helps visually group all levels of a 
factor variable together, making the plot easier to read especially with 
many multi-level factors.

\strong{Model Statistics Display:}

The footer shows key diagnostic information:
\itemize{
  \item \strong{Observations analyzed}: Observations used in fitting, the 
    total supplied, and the percentage retained (accounting for missing 
    values)
  \item \strong{Null/Residual Deviance}: Model fit improvement
  \item \strong{Pseudo-\emph{R}\eqn{^2}}: McFadden \emph{R}\eqn{^2} = 1 - (log L_1 / log L_2)
  \item \strong{AIC}: For model comparison (lower is better)
}

For logistic regression, concordance (C-statistic/AUC) may also be displayed 
if available.

\strong{Saving Plots:}

Use \code{forestsave()}, which applies the recommended dimensions and
selects a graphics device suited to the format:
\preformatted{
  p <- glmforest(model, data)
  forestsave(p, "forest.pdf")
}

Or specify custom dimensions:
\preformatted{
forestsave(p, "forest.png", width = 12, height = 8, dpi = 300)
}
}
\examples{
data(clintrial)
data(clintrial_labels)

# Create example model
model1 <- glm(os_status ~ age + sex + bmi + treatment,
              data = clintrial, family = binomial)

# Example 1: Basic logistic regression forest plot
p <- glmforest(model1, data = clintrial)

\donttest{

old_width <- options(width = 180)

# Example 2: With custom variable labels
plot2 <- glmforest(
    x = model1,
    data = clintrial,
    title = "Risk Factors for Mortality",
    labels = clintrial_labels
)

# Example 3: Indented layout with formatting options
plot3 <- glmforest(
    x = model1,
    data = clintrial,
    indent_groups = TRUE,
    zebra_stripes = TRUE,
    color = "#D62728",
    labels = clintrial_labels
)

# Example 4: Condensed layout for many binary variables
model4 <- glm(os_status ~ age + sex + smoking + hypertension + 
                  diabetes + surgery,
              data = clintrial,
              family = binomial)

plot4 <- glmforest(
    x = model4,
    data = clintrial,
    condense_table = TRUE,
    labels = clintrial_labels
)
# Binary variables shown in single rows

# Example 5: Poisson regression for count data
model5 <- glm(ae_count ~ age + treatment + diabetes + surgery,
               data = clintrial,
               family = poisson)

plot5 <- glmforest(
    x = model5,
    data = clintrial,
    title = "Rate Ratios for Adverse Events",
    labels = clintrial_labels
)

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

options(old_width)

}
}
\seealso{
\code{\link{autoforest}} for automatic model detection,
\code{\link{coxforest}} for Cox proportional hazards forest plots,
\code{\link{lmforest}} for linear model forest plots,
\code{\link{uniforest}} for univariable screening forest plots,
\code{\link{multiforest}} for multi-outcome forest plots,
\code{\link[stats]{glm}} for fitting GLMs,
\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[=lmforest]{lmforest()}},
\code{\link[=multiforest]{multiforest()}},
\code{\link[=recdims]{recdims()}},
\code{\link[=uniforest]{uniforest()}}
}
\concept{visualization functions}
