% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/coxforest.R
\name{coxforest}
\alias{coxforest}
\title{Create Forest Plot for Cox Proportional Hazards Models}
\usage{
coxforest(
  x,
  data = NULL,
  title = "Cox Proportional Hazards Model",
  effect_label = "Hazard Ratio",
  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 = "#8A61D8",
  qc_footer = TRUE,
  units = "in",
  number_format = NULL
)
}
\arguments{
\item{x}{Either a fitted Cox model object (class \code{coxph} or \code{coxme}), 
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{"Cox Proportional Hazards Model"}. Use descriptive titles 
for publication.}

\item{effect_label}{Character string for the effect measure label on the 
forest plot axis. Default is \code{"Hazard Ratio"}. Alternatives might include 
"HR" for space-constrained plots.}

\item{digits}{Integer specifying the number of decimal places for hazard ratios 
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}. Used for optimizing layout. Default is \code{NULL} 
(automatic). Recommended: 10-16 inches.}

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

\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 (60\% table, 
40\% forest plot).}

\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{show_events}{Logical. If \code{TRUE}, includes a column showing the 
number of events (deaths, failures) for each group. Critical for survival 
analysis interpretation. Default is \code{TRUE}.}

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

\item{condense_table}{Logical. If \code{TRUE}, condenses binary variables to 
show only the non-reference level (\emph{e.g.,} "Yes" for Yes/No variables), with 
the variable name indicating the displayed level. This creates a more compact 
table for models with many binary predictors. 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 for improved readability. 
Default is \code{TRUE}.}

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

\item{labels}{Named character vector providing custom display labels for 
variables. Example: \code{c(age = "Age (years)", stage = "Disease Stage")}. 
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 hazard ratio point 
estimates in the forest plot. Default is \code{"#8A61D8"} (purple). Use 
hex codes or R color names.}

\item{qc_footer}{Logical. If \code{TRUE}, displays model quality control
statistics in the footer (events analyzed, global log-rank \emph{p}-value,
concordance index, AIC). Default is \code{TRUE}.}

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

\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 hazard ratios from a Cox proportional hazards 
survival model. The plot integrates variable names, group levels, sample sizes, 
event counts, hazard ratios with confidence intervals, \emph{p}-values, and model 
diagnostics in a single comprehensive visualization designed for manuscripts 
and presentations.
}
\details{
\strong{Survival-Specific Features:}

The Cox forest plot includes several survival analysis-specific components:
\itemize{
  \item \strong{Event counts}: Number of events (deaths, failures) shown for 
    each predictor category, critical for assessing statistical power
  \item \strong{Hazard ratios}: Always exponentiated coefficients (never raw), 
    interpreted as the multiplicative change in hazard
  \item \strong{Log scale}: Forest plot uses log scale for HR (reference line at 1)
  \item \strong{Model diagnostics}: Includes concordance (C-index), global 
    log-rank test \emph{p}-value, and AIC
}

\strong{Plot Components:}

\enumerate{
  \item \strong{Title}: Centered at top
  \item \strong{Data Table} (left): Contains:
    \itemize{
      \item Variable and Group columns
      \item n: Sample sizes by group
      \item Events: Event counts by group (critical for survival)
      \item aHR (95\% CI); \emph{p}-value: Adjusted hazard ratios with CIs and \emph{p}-values
    }
  \item \strong{Forest Plot} (right):
    \itemize{
      \item Point estimates (squares sized by sample size)
      \item 95\% confidence intervals
      \item Reference line at HR = 1
      \item Log scale for hazard ratios
    }
  \item \strong{Model Statistics} (footer):
    \itemize{
      \item Events analyzed (with total events and percentage)
      \item Global log-rank test \emph{p}-value
      \item Concordance (C-index) with standard error
      \item AIC
    }
}

\strong{Interpreting Hazard Ratios:}

\itemize{
  \item \strong{HR = 1}: No effect on hazard (reference)
  \item \strong{HR > 1}: Increased hazard (worse survival)
  \item \strong{HR < 1}: Decreased hazard (better survival)
  \item Example: HR = 2.0 means twice the hazard of the event at any time
}

\strong{Event Counts:}

The "Events" column is particularly important in survival analysis:
\itemize{
  \item Indicates the number of actual events (not censored observations) 
    in each group
  \item Essential for assessing statistical power
  \item Categories with very few events may have unreliable HR estimates
  \item The footer shows events analyzed, total events, and percentage 
    in the original data
}

\strong{Concordance (C-index):}

The concordance statistic displayed in the footer indicates discrimination:
\itemize{
  \item Range: 0.5 to 1.0
  \item 0.5 = random prediction (coin flip)
  \item 0.7-0.8 = acceptable discrimination
  \item > 0.8 = excellent discrimination
  \item Standard error provided for confidence interval calculation
}

\strong{Global Log-Rank Test:}

The global \emph{p}-value tests the null hypothesis that all coefficients are zero:
\itemize{
  \item Significant \emph{p}-value (< 0.05) indicates the model as a whole predicts survival
  \item Non-significant global test doesn't preclude significant individual 
    predictors
  \item Based on the score (log-rank) test
}

\strong{Stratification and Clustering:}

If the model includes stratification (\code{strata()}) or clustering 
(\code{cluster()}):
\itemize{
  \item Stratified variables are not shown in the forest plot (they don't 
    have HRs)
  \item Clustering affects standard errors but not point estimates
  \item Both are handled automatically by the function
}

\strong{Proportional Hazards Assumption:}

The forest plot assumes proportional hazards (constant HR over time). Users 
should verify this assumption using:
\itemize{
  \item \code{cox.zph(model)} for testing
  \item Stratification for variables violating the assumption
  \item Time-dependent coefficients if needed
}
}
\examples{
data(clintrial)
data(clintrial_labels)
library(survival)

# Create example model
model1 <- coxph(
    survival::Surv(os_months, os_status) ~ age + sex + treatment,
    data = clintrial)

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

\donttest{

old_width <- options(width = 180)

# Example 2: With custom labels and title
plot2 <- coxforest(
    x = model1,
    data = clintrial,
    title = "Prognostic Factors for Overall Survival",
    labels = clintrial_labels
)

# Example 3: Comprehensive model with indented layout
model3 <- coxph(
    Surv(os_months, os_status) ~ age + sex + bmi + smoking + 
        treatment + stage + grade,
    data = clintrial
)

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

# Example 4: Condensed layout for many binary predictors
model4 <- coxph(
    Surv(os_months, os_status) ~ age + sex + smoking + 
        hypertension + diabetes + surgery,
    data = clintrial
)

plot4 <- coxforest(
    x = model4,
    data = clintrial,
    condense_table = TRUE,
    labels = clintrial_labels
)

# Example 5: Stratified Cox model
model5 <- coxph(
    Surv(os_months, os_status) ~ age + sex + treatment + strata(site),
    data = clintrial
)

plot5 <- coxforest(
    x = model5,
    data = clintrial,
    title = "Stratified by Study Site",
    labels = clintrial_labels
)

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

options(old_width)

}
}
\seealso{
\code{\link{autoforest}} for automatic model detection,
\code{\link{glmforest}} for logistic/GLM 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[survival]{coxph}} for fitting Cox models,
\code{\link{fit}} for regression modeling,
  \code{\link{forestsave}} for saving with recommended dimensions

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