A density plot is a smoothed histogram that displays the distribution of a continuous or numeric variable as a curve. Its x-axis shows values; its y-axis shows probability density rather than counts. section 4.5.1 section 5.5.1
Use density plots to:
- See the underlying shape of a distribution without choosing histogram bin counts. section 4.5.1
- Identify peaks or modes and assess whether values appear skewed or symmetric. section 4.5.1
- Compare the mean and median with vertical reference lines, while remembering that density tracks frequency rather than reporting counts. section 4.5.1
NBA free-agent distributions
To inspect shortlisted free agents, plot annual salary, win shares, and age with ggplot2. A salary plot can use geom_density(alpha = .3), add mean and median lines with geom_vline(), format salary labels with scales, and combine the three plots vertically. The same workflow visualizes hustle$deflections; paired with a Shapiro-Wilk test returning p = 0.4235, its plot supports an approximately normal distribution. section 4.5.1 section 5.5.1
p1 <- ggplot(free_agents, aes(x = annual_salary)) +
geom_density(alpha = .3, fill = "salmon") +
geom_vline(aes(xintercept = mean(annual_salary, na.rm = TRUE)),
color = "red", linetype = "longdash", size = .8) +
geom_vline(aes(xintercept = median(annual_salary, na.rm = TRUE)),
color = "blue", linetype = "longdash", size = .8) +
labs(title = "Annual Salary Distribution",
subtitle = "Shortlisted Free Agents",
x = "Annual Salary",
y = "Density",
caption = "Salary data is illustrative only") +
scale_x_continuous(labels = comma) +
theme(plot.title = element_text(face = "bold")) +
annotate("text", x = 18000000,
y = .000000025, label = "Mean", color = "black",
size = 4, fontface = "bold", angle = 90) +
annotate("text", x = 14000000,
y = .000000025, label = "Median", color = "black",
size = 4, fontface = "bold", angle = 90)
Run the supplied ggplot2 example to build an annotated annual-salary density plot with transparent fill, mean and median markers, labels, and formatted x-axis values. section 4.5.1
