Learn R Programming

pubrplot (version 0.0.1)

plot_scatter: Scatter Plot with Linear Regression and Equation Annotation

Description

This function creates a scatter plot of a numeric outcome against a numeric predictor, optionally grouped by a factor (by). A linear regression line is added with optional standard error (SE) shading, and the regression equation and R² value are displayed on the plot.

Usage

plot_scatter(
  data,
  outcome,
  predictor,
  by = NULL,
  point_color = "#377eb8",
  line_color = "#e41a1c",
  se_fill = "#e41a1c55",
  line_size = 1,
  se = TRUE,
  facet_scales = "free",
  eq_position = c(0.05, 0.95),
  ncol_by = NULL
)

Value

A ggplot2 object of the scatter plot with regression line and annotated equation.

Arguments

data

A data frame containing the variables to plot.

outcome

Character string. Name of the numeric outcome variable.

predictor

Character string. Name of the numeric predictor variable.

by

Character string, optional. Name of a factor variable for grouping/faceting.

point_color

Color for the scatter plot points (default: "#377eb8").

line_color

Color for the regression line (default: "#e41a1c").

se_fill

Fill color for the confidence interval shading around the regression line (default: "#e41a1c55").

line_size

Numeric. Line width for the regression line (default: 1).

se

Logical. Whether to display the standard error shading around the regression line (default: TRUE).

facet_scales

Character. Scales argument for facet_wrap ("free", "fixed", "free_x", "free_y") (default: "free").

eq_position

Numeric vector of length 2. Relative position of regression equation on the plot: c(x_pos, y_pos) (default: c(0.05, 0.95)).

ncol_by

Numeric. Number of columns for faceting (passed to facet_wrap) (default: NULL, automatic).

Examples

Run this code
# Basic scatter plot with regression line and equation
plot_scatter(mtcars, "mpg", "wt")

# Scatter plot grouped by cylinder
plot_scatter(mtcars, "mpg", "wt", by = "cyl",
           point_color = "blue",
           line_color = "red",
           se_fill = "#ff000055",
           line_size = 0.9,
           se = TRUE,
           eq_position = c(0.5, 0.95),
           ncol_by = 2)

Run the code above in your browser using DataLab