In ggplot2, ylim() specifies the visible range of a plot’s y-axis. It is especially useful when comparing charts: applying the same limits prevents differing scales from making equal-sized bars appear misleadingly different. section 2.5.5
Use ylim() to control the vertical space available for bars and labels:
- Write ylim(lower, upper), such as ylim(0, 35), to standardize two win-share bar charts. section 2.5.5
- Choose an upper limit that leaves room for geom_text() labels placed above the bars. section 14.3
- Remember that axis choices affect visual comparison: unequal scales can conceal differences between means and medians. section 2.5.5
Compare average and median career win shares
p5 <- ggplot(tenth_tibble, aes(x = Born2, y = meanWS)) + geom_bar(stat = "identity") + geom_text(aes(label = trunc(meanWS), vjust = -0.3)) + ylim(0, 35) p6 <- ggplot(tenth_tibble, aes(x = Born2, y = medianWS)) + geom_bar(stat = "identity") + geom_text(aes(label = trunc(medianWS), vjust = -0.3)) + ylim(0, 35) p5 + p6 + plot_layout(ncol = 2) Both charts now use the same vertical scale, making the differences between average and median win shares easier to judge. section 2.5.5
p5 <- ggplot(tenth_tibble, aes(x = Born2, y = meanWS)) +
geom_bar(stat = "identity", width = .5, fill = "darkorchid4") +
labs(title = "Average Win Shares by Place of Birth",
subtitle = "2000-09 NBA Drafts",
x = "Where Born",
y = "Average Career Win Shares") +
geom_text(aes(label = trunc(meanWS), vjust = -0.3)) +
ylim(0, 35) +
theme(plot.title = element_text(face = "bold"))
p6 <- ggplot(tenth_tibble, aes(x = Born2, y = medianWS)) +
geom_bar(stat = "identity", width = .5, fill = "sienna1") +
labs(title = "Median Win Shares by Place of Birth",
subtitle = "2000-09 NBA Drafts",
x = "Where Born",
y = "Median Career Win Shares") +
geom_text(aes(label = trunc(medianWS), vjust = -0.3)) +
ylim(0, 35) +
theme(plot.title = element_text(face = "bold"))
Inspect the complete ggplot2 code for two NBA win-share bar charts using ylim(0, 35), text labels, and matching styling. section 2.5.5
