0
0
R-programmingHow-ToBeginner · 3 min read

How to Add Title to ggplot in R: Simple Guide

To add a title to a ggplot chart in R, use the ggtitle() function or the labs(title = "Your Title") function. Both add a main title above the plot to describe what the chart shows.
📐

Syntax

The main ways to add a title to a ggplot are:

  • ggtitle("Your Title"): Adds a title string above the plot.
  • labs(title = "Your Title"): Adds a title using the labs() function which can also set axis labels.

Both are added to the plot object using the + operator.

r
ggplot(data) + geom_point(aes(x, y)) + ggtitle("Your Title")

# or

ggplot(data) + geom_point(aes(x, y)) + labs(title = "Your Title")
💻

Example

This example shows how to create a scatter plot with a title using ggtitle() and labs().

r
library(ggplot2)

# Sample data
data <- data.frame(x = 1:5, y = c(3, 7, 8, 5, 6))

# Using ggtitle()
plot1 <- ggplot(data) +
  geom_point(aes(x, y)) +
  ggtitle("Scatter Plot with ggtitle")

print(plot1)

# Using labs()
plot2 <- ggplot(data) +
  geom_point(aes(x, y)) +
  labs(title = "Scatter Plot with labs")

print(plot2)
Output
[Plots displayed: Scatter Plot with ggtitle and Scatter Plot with labs]
⚠️

Common Pitfalls

Common mistakes when adding titles to ggplot include:

  • Forgetting to use the + operator to add ggtitle() or labs() to the plot.
  • Passing the title as a separate argument inside ggplot() instead of using ggtitle() or labs().
  • Using quotes incorrectly or missing them around the title string.

Always add the title function after the plot layers with +.

r
library(ggplot2)

data <- data.frame(x = 1:3, y = c(2, 4, 6))

# Wrong: title inside ggplot()
# ggplot(data, title = "Wrong Title") + geom_point(aes(x, y))

# Right:
ggplot(data) + geom_point(aes(x, y)) + ggtitle("Correct Title")
📊

Quick Reference

FunctionPurposeExample Usage
ggtitle()Add main title above the plotggplot(data) + geom_point(aes(x, y)) + ggtitle("Title")
labs()Add title and axis labelsggplot(data) + geom_point(aes(x, y)) + labs(title = "Title", x = "X-axis", y = "Y-axis")

Key Takeaways

Use ggtitle() or labs(title = "") to add a title to ggplot charts.
Always add the title function with + after the plot layers.
Do not put the title inside ggplot() function arguments.
labs() can set titles and axis labels together.
Remember to enclose the title text in quotes.