The viz_density() function creates kernel density
estimate plots, which provide a smoothed visualization of the
distribution of a continuous variable. Unlike histograms that use
discrete bins, density plots show a continuous estimate of the
probability density function.
Density plots are particularly useful for: - Visualizing distribution shapes without binning artifacts - Comparing multiple distributions on the same plot - Identifying multimodal distributions
Create a simple density plot showing the distribution of age:
Compare distributions across groups by adding a
group_var:
Control the transparency of the filled area with
fill_opacity (0 = transparent, 1 = opaque):
The bandwidth parameter controls how smooth the density
estimate is. Lower values = more detail, higher values = smoother.
Compare age distributions across race categories:
# Filter to categories with sufficient data
gss_race <- gss %>%
filter(!is.na(race)) %>%
mutate(race = as.character(haven::as_factor(race)))
plot <- viz_density(
data = gss_race,
x_var = "age",
group_var = "race",
title = "Age Distribution by Race",
x_label = "Age (years)",
fill_opacity = 0.3
)
plotUse include_na = TRUE to show NA values as an explicit
category:
# Create some NAs for demonstration
gss_with_na <- gss %>%
mutate(sex_with_na = if_else(row_number() %% 10 == 0, NA_character_, as.character(haven::as_factor(sex))))
plot <- viz_density(
data = gss_with_na,
x_var = "age",
group_var = "sex_with_na",
title = "Age Distribution by Sex (Including Missing)",
include_na = TRUE,
na_label = "Not Reported"
)
plotControl the order of groups in the legend:
gss_degree <- gss %>%
filter(!is.na(degree)) %>%
mutate(degree = as.character(haven::as_factor(degree)))
plot <- viz_density(
data = gss_degree,
x_var = "age",
group_var = "degree",
title = "Age Distribution by Education",
group_order = c("graduate", "bachelor", "junior college", "high school", "lt high school")
)
plotThe viz_density() function provides a flexible way to
visualize continuous distributions with these key features:
data and
x_vargroup_var to
compare distributionsfill_opacity,
color_palette, and show_rugbandwidth to
control detail levelinclude_na
and na_labelgroup_order