Learn R Programming

statuser (version 0.1.9)

plot_density: Plot density of a variable, optionally by another variable

Description

Plots the distribution of a variable by group, simply: plot_density(y ~ x)

Usage

plot_density(
  formula,
  y = NULL,
  data = NULL,
  order = NULL,
  show_means = TRUE,
  ...
)

Value

Invisibly returns a list with the following element:

densities

A named list of density objects (class "density"), one for each group. Each density object contains x (evaluation points), y (density estimates), bw (bandwidth), and other components as returned by density. If no grouping variable is provided, the list contains a single element named "all".

The function is primarily called for its side effect of creating a plot.

Arguments

formula

Either the single variable name y or a formula like y ~ x. Alternatively, pass a single vector for a simple density plot.

y

An optional second vector to compare with formula. When provided, creates a comparison plot of two variables. This allows syntax like plot_density(y1, y2) to compare two vectors.

data

An optional data frame containing the variables in the formula.

order

Controls the order in which groups appear in the plot and legend. Use -1 to reverse the default order. Alternatively, provide a vector specifying the exact order (e.g., c("B", "A", "C")). If NULL (default), groups are ordered by their factor levels (if the grouping variable is a factor) or sorted alphabetically/numerically. Only applies when using grouped plots.

show_means

Logical. If TRUE (default), shows points at means.

...

Additional arguments passed to plotting functions.

Details

Plot parameters like col, lwd, lty, and pch can be specified as:

  • A single value: applied to all groups

  • A vector: applied to groups in order of unique group values

Examples

Run this code
# Basic usage with formula syntax (no grouping)
y <- rnorm(100)
plot_density(y)

# With grouping variable
group <- rep(c("A", "B", "C"), c(30, 40, 30))
plot_density(y ~ group)

# With custom colors (scalar - same for all)
plot_density(y ~ group, col = "blue")

# With custom colors (vector - different for each group)
plot_density(y ~ group, col = c("red", "green", "blue"))

# Multiple parameters
plot_density(y ~ group, col = c("red", "green", "blue"), lwd = c(1, 2, 3))

# With line type
plot_density(y ~ group, col = c("red", "green", "blue"), lty = c(1, 2, 3), lwd = 2)

# Using data frame
df <- data.frame(value = rnorm(100), group = rep(c("A", "B"), 50))
plot_density(value ~ group, data = df)
plot_density(value ~ group, data = df, col = c("red", "blue"))

# Compare two vectors
y1 <- rnorm(50)
y2 <- rnorm(50, mean = 1)
plot_density(y1, y2)

Run the code above in your browser using DataLab