How to change legend title in ggplot in R?
A simple way to rename a legend title in ggplot2 is by using the labs()
function:
library(ggplot2) # Example dataset df <- data.frame( x = 1:5, y = c(2, 4, 3, 6, 5), group = factor(c("A", "A", "B", "B", "A")) ) # Basic plot ggplot(df, aes(x = x, y = y, color = group)) + geom_line() + labs(color = "New Legend Title")
labs(color = "New Legend Title")
changes the legend heading for the color aesthetic.
Using Scale Functions
If you’re specifying custom color scales, you can rename your legend title directly in the scale function. For instance:
ggplot(df, aes(x = x, y = y, color = group)) + geom_line() + scale_color_discrete(name = "Group Legend Title")
Other aesthetics (like fill
) work similarly with scale_fill_discrete(name = "...")
, and continuous scales use scale_color_continuous(name = "...")
.
Additional Tips
- Make sure you’ve properly mapped the aesthetic (e.g.,
color
vs.fill
). - For multiple legends in a single plot, adjust each aesthetic’s scale function or
labs()
argument accordingly.
Further Learning
For broader coding interview prep, check out
- Grokking the Coding Interview: Patterns for Coding Questions
- Grokking Data Structures & Algorithms for Coding Interviews
And if you’re aiming to master large-scale system design, consider Grokking System Design Fundamentals. For personalized feedback on your coding approach, visit Coding Mock Interviews, where ex-FAANG engineers guide you one-on-one. You can also find more insights and tutorials on the DesignGurus.io YouTube channel.