How to Change Legend Title in R ggplot2

To change the legend title in R ggplot2 depending on the type of aesthetic mapping used in your plot, you can use the “labs()” or “scale_fill_discrete()” function.

Method 1: Using the labs() function

The easiest way to change a legend title in ggplot2 is to use the “labs()” function. The labs() function changes the axis, legend, and plot labels in ggplot2. It adds or changes the axis, legend, and plot labels.

Example

library(ggplot2)

# Create sample data
data <- data.frame(
  Category = c("A", "B", "C", "D", "E"),
  Values = c(10, 25, 35, 45, 15),
  Group = c(
    "Group 1", "Group 2", "Group 1",
    "Group 2", "Group 1"
  )
 )

# Create ggplot2 bar chart with fill aesthetic
plot <- ggplot(data, aes(x = Category, y = Values, fill = Group)) +
  geom_bar(stat = "identity", position = "dodge")

# Change the legend title using labs()
plot <- plot + labs(fill = "New Legend Title")

# Print the plot
print(plot)

Output

Change Legend Title in ggplot2

We created a barplot using the sample data, with the fill aesthetic mapped to the Group variable. The legend title is then changed to “New Legend Title” using the labs() function with the fill argument.

Method 2: Using the scale_fill_discrete() function

Alternatively, modify the legend title using the scale_fill_* or scale_color_* functions. For example, we will use the scale_fill_discrete() function to change the legend title in ggplot2.

plot <- plot + scale_fill_discrete(name = "New Legend Title")

We used a scale_fill_discrete() function that takes a name argument to change the legend title. If you used a different aesthetic mapping, like the color aesthetic, you could use the corresponding scale_color_* function (e.g., scale_color_discrete(name = “New Legend Title”)).

See the complete code below.

library(ggplot2)

# Create sample data
data <- data.frame(
  Category = c("A", "B", "C", "D", "E"),
  Values = c(10, 25, 35, 45, 15),
  Group = c(
    "Group 1", "Group 2", "Group 1",
    "Group 2", "Group 1"
  )
)

# Create ggplot2 bar chart with fill aesthetic
plot <- ggplot(data, aes(x = Category, y = Values, fill = Group)) +
   geom_bar(stat = "identity", position = "dodge")

# Change the legend title using labs()
plot <- plot + scale_fill_discrete(name = "New Legend Title")

# Print the plot
print(plot)

Output

Using the scale_fill_discrete() function to change legend title in ggplot2

In the above code example, we created a bar chart using the sample data, with the fill aesthetic mapped to the Group variable. The legend title is then updated to “New Legend Title” using the scale_fill_discrete() function with the name argument.

That’s it.

Leave a Comment