How to Add Labels to ggplot in R: Titles, Axis, and Captions
To add labels in
ggplot2, use the labs() function to set titles, axis labels, and captions. You can also use ggtitle() for the main title and xlab() and ylab() for axis labels individually.Syntax
The main function to add labels in ggplot2 is labs(). It lets you add or change the plot title, subtitle, axis labels, and caption all at once.
title: Main title of the plotsubtitle: Subtitle below the main titlex: Label for the x-axisy: Label for the y-axiscaption: Text shown at the bottom right of the plot
Alternatively, you can use ggtitle() for the title, and xlab() and ylab() for axis labels separately.
r
ggplot(data, aes(x, y)) + geom_point() + labs(title = "Main Title", subtitle = "Subtitle here", x = "X-axis Label", y = "Y-axis Label", caption = "Caption text")
Example
This example shows how to create a scatter plot with ggplot2 and add a main title, axis labels, subtitle, and caption using labs().
r
library(ggplot2) # Sample data data <- data.frame( x = 1:10, y = c(2, 5, 7, 8, 12, 14, 15, 18, 20, 22) ) # Create plot with labels plot <- ggplot(data, aes(x = x, y = y)) + geom_point(color = "blue") + labs( title = "Sample Scatter Plot", subtitle = "Showing points from x and y", x = "X Values", y = "Y Values", caption = "Data source: Example" ) print(plot)
Output
[A scatter plot with blue points, titled 'Sample Scatter Plot', subtitle 'Showing points from x and y', x-axis labeled 'X Values', y-axis labeled 'Y Values', and caption 'Data source: Example' at bottom right]
Common Pitfalls
Some common mistakes when adding labels in ggplot2 include:
- Forgetting to add
labs()orggtitle()inside the plot chain, so labels don't appear. - Using
titleinsideaes()which won't work because labels are not aesthetics. - Overlapping labels or very long text that can clutter the plot.
- Not loading
ggplot2library before using its functions.
Correct usage example:
r
# Wrong: title inside aes (won't show title)
ggplot(data, aes(x, y, title = "Wrong Title")) + geom_point()
# Right: use labs() for title
ggplot(data, aes(x, y)) + geom_point() + labs(title = "Correct Title")Quick Reference
| Function | Purpose | Example Usage |
|---|---|---|
| labs() | Add or change plot title, subtitle, axis labels, caption | labs(title = "Title", x = "X axis", y = "Y axis", caption = "Caption") |
| ggtitle() | Add or change main plot title | ggtitle("Main Title") |
| xlab() | Add or change x-axis label | xlab("X Axis Label") |
| ylab() | Add or change y-axis label | ylab("Y Axis Label") |
Key Takeaways
Use labs() to add or customize titles, axis labels, subtitles, and captions in ggplot.
Avoid placing labels inside aes(); labels are not aesthetics.
ggtitle(), xlab(), and ylab() can add titles and axis labels individually.
Always load ggplot2 library before creating plots with labels.
Keep labels clear and concise to avoid cluttering the plot.