| plot_density | R Documentation |
Plots the distribution of a variable by group, simply: plot_density(y ~ x)
plot_density(
formula,
y2 = NULL,
data = NULL,
order = NULL,
show_means = TRUE,
...
)
formula |
Two possible uses (similar to
|
y2 |
optional second variable when contrasting two variables |
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 |
show_means |
Logical. If TRUE (default), shows points at means. |
... |
Additional arguments passed to plotting functions. |
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
Invisibly returns a list with the following element:
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.
# 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)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.