Learn R Programming

pubrplot (version 0.0.1)

plot_line: Line Plot with Error Bars by Group and Time

Description

This function creates a line plot showing the mean of a numeric variable over time for different groups, with optional error bars (standard deviation, standard error, or 95% confidence interval). Multiple groups are displayed on the same plot with customizable colors, point shapes, and line thickness.

Usage

plot_line(
  data,
  var,
  time,
  group,
  error = c("sd", "se", "ci"),
  err.mult = 1.5,
  point.shape = 19,
  point.size = 3,
  line.size = 1,
  color.lines = c("red", "blue"),
  show.mean = FALSE,
  text.size = 3.5,
  err.width = 0.05,
  x.lab = "Time",
  y.lab = NULL,
  title = NULL,
  theme_fun = ggthemes::theme_stata
)

Value

A ggplot object displaying the line plot with optional error bars for multiple groups.

Arguments

data

A data frame containing the variables to plot.

var

A numeric variable to summarize and plot.

time

A variable representing time points (x-axis). Converted to factor if not already.

group

A grouping variable (color/line grouping) for the plot.

error

Type of error to display: "sd" (standard deviation), "se" (standard error), or "ci" (95% confidence interval). Default is "sd".

err.mult

Numeric multiplier for the error bars. Default is 1.5.

point.shape

Shape of the points. Default is 19 (solid circle).

point.size

Size of the points. Default is 3.

line.size

Thickness of the lines. Default is 1.

color.lines

Vector of colors for the lines/groups. Default is c("red", "blue").

show.mean

Logical; if TRUE, mean values can optionally be displayed above points. Default is FALSE.

text.size

Size of mean value text labels (if show.mean = TRUE). Default is 3.5.

err.width

Width of the error bars. Default is 0.05.

x.lab

Label for the x-axis. Default is "Time".

y.lab

Label for the y-axis. If NULL, uses the name of var.

title

Plot title. Default is NULL.

theme_fun

ggplot2 theme function to customize plot appearance. Default is ggthemes::theme_stata.

Examples

Run this code
set.seed(123)
n_subj <- 10
time_points <- c("T1","T2","T3")
groups <- c("DrugA","DrugB")

df <- expand.grid(
  id = 1:n_subj,
  time = time_points,
  group = groups
)

# Arrange by group, id, time
df <- dplyr::arrange(df, group, id, time)

# Add BMI column
df <- dplyr::mutate(df,
  BMI = dplyr::case_when(
    time == "T1" & group == "DrugA" ~ 29 + stats::rnorm(dplyr::n(), 0, 0.3),
    time == "T2" & group == "DrugA" ~ 26 + stats::rnorm(dplyr::n(), 0, 0.3),
    time == "T3" & group == "DrugA" ~ 22 + stats::rnorm(dplyr::n(), 0, 0.3),
    time == "T1" & group == "DrugB" ~ 28 + stats::rnorm(dplyr::n(), 0, 0.3),
    time == "T2" & group == "DrugB" ~ 25 + stats::rnorm(dplyr::n(), 0, 0.2),
    time == "T3" & group == "DrugB" ~ 21 + stats::rnorm(dplyr::n(), 0, 0.2)
  )
)

Run the code above in your browser using DataLab