scale_fill_discrete() configures the discrete fill scale in a ggplot2 chart. Use it when a categorical variable controls fill colors and the default legend name or labels are unclear. The function can replace technical variable names and factor levels with reader-friendly wording. section 14.5.1 section 18.3
Common uses include:
- Rename a legend with the name argument, such as replacing o_pts_cat with “Points Allowed Z-Score.” section 14.5.1
- Replace factor-level labels with interpretable ranges through the labels argument, such as “< -1,” “-1 to 0,” “0 to 1,” and “> 1.” section 14.5.1
- Create a legend for a categorical fill mapping, then position that legend elsewhere with theme(legend.position = "bottom"). section 18.3
Clarifying an NBA boxplot legend
p3 <- ggplot(nba_stats, aes(x = o_pts_cat, y = z_wins, fill = o_pts_cat)) + geom_boxplot(notch = TRUE, alpha = 0.5) + scale_fill_discrete( name = "Points\nAllowed\nZ-Score", labels = c("< -1", "-1 to 0", "0 to 1", "> 1") ) The plot compares standardized regular-season wins across standardized points-allowed categories. The customized legend explains the categories more clearly than the default variable name and factor levels. section 14.5.1
Labeling salary-cap categories
p1 <- ggplot(new_cap, aes(x = season, y = cap, fill = type)) + geom_col(width = 0.6) + scale_fill_discrete( name = "", labels = c("Adjusted Dollars", "Real Dollars") ) + theme(legend.position = "bottom") Here, the legend distinguishes real and inflation-adjusted salary-cap values while omitting its title. section 18.3
p3 <- ggplot(nba_stats, aes(x = o_pts_cat, y = z_wins, fill = o_pts_cat)) +
geom_boxplot(notch = TRUE, alpha = 0.5) +
labs(title = "Points Allowed vs. Wins",
subtitle = "2008-17",
x = "Standardized Points Allowed Category",
y = "Standardized Regular Season Wins") +
stat_summary(fun = mean, geom = "point",
shape = 20, size = 8, color = "white", fill = "white") +
theme(legend.position = "bottom") +
scale_fill_discrete(name = "Points\nAllowed\nZ-Score",
labels = c("< -1", "-1 to 0", "0 to 1","> 1")) +
theme(plot.title = element_text(face = "bold"))
Inspect the complete boxplot specification, including the fill mapping, custom legend title, category labels, and legend placement. section 14.5.1
