How to Remove a Legend in ggplot2 (With Examples)

Here are two common ways to remove a legend in ggplot2:

  1. Using theme() to remove all legends
  2. Using guides() to remove specific legends

Method 1: Using theme() to remove all legends

To remove all legends from a plot, you can set the legend.position to “none”.

Example 1: Set legend.position argument to “none”

library(ggplot2)

# Create a sample data frame
df <- data.frame(
  x = rnorm(100),
  y = rnorm(100),
  category = sample(letters[1:3], 100, replace = TRUE)
)

# Create a scatter plot without a legend
plot <- ggplot(df, aes(x = x, y = y, color = category)) +
  geom_point() +
  theme(legend.position = "none")

# Display the plot
plot

Output

Visual representation of Set legend.position = none

By adding theme(legend.position = “none”), we are instructing ggplot2 not to display the legend that would normally show the color mapping for the category variable.

Example 2: Line Plot without Legend

# Load the necessary libraries
library(ggplot2)

# Create a sample data frame
df <- data.frame(
  time = 1:10,
  value = cumsum(rnorm(10)),
  group = rep(1:2, each = 5)
)

# Create a line plot without a legend
plot <- ggplot(df, aes(x = time, y = value, color = as.factor(group))) +
  geom_line() +
  theme(legend.position = "none")

# Display the plot
plot

Output

Visual Representation of Line Plot without Legend

Example 3: Bar Plot without Legend

# Load the necessary libraries
library(ggplot2)

# Create a sample data frame
df <- data.frame(
  category = rep(letters[1:3], each = 4),
  value = runif(12)
)

# Create a bar plot without a legend
plot <- ggplot(df, aes(x = category, y = value, fill = category)) +
  geom_bar(stat = "identity") +
  theme(legend.position = "none")

# Display the plot
plot

Output

Visual representation of Bar Plot without Legend

Method 2: Using guides() to remove specific legends

To remove a specific legend (for example, the legend for a particular aesthetic like color, fill, size, etc.), use the guides() function and set the guide for that aesthetic to FALSE:

# Example plot with multiple legends
p <- ggplot(mpg, aes(x = displ, y = hwy, color = class, size = cyl)) +
      geom_point()

# Remove only the color legend
p <- p + guides(color = "none")

# Alternatively, remove only the size legend
# p <- p + guides(size = "none")

# Display the plot
print(p)

Output

Visual representation of using guides() to remove specific legends

That’s it!

Related posts

Change the Legend Title in ggplot2

Change Legend Size in ggplot2

Change Legend Labels in ggplot2

Leave a Comment