How to Remove Legend from a GGPlot



How to Remove Legend from a GGPlot

This article describes how to remove legend from a plot created using the ggplot2 package.

You will learn how to:

  • Hide the entire legend to create a ggplot with no legend.
  • Remove the legend for a specific aesthetic.

Related Book

GGPlot2 Essentials for Great Data Visualization in R

Prerequisites

Load required packages and set the theme function theme_minimal() as the default theme:

library(ggplot2) 
theme_set(theme_minimal())

Create a basic plot

Create a box plot using the ToothGrowth data set.

ToothGrowth$dose <- as.factor(ToothGrowth$dose)
p <- ggplot(ToothGrowth, aes(x = dose, y = len))+ 
  geom_boxplot(aes(fill = dose)) + 
  scale_fill_viridis_d()
p

GGPlot with no legend

During the plot creation, you can decide to turn off legends by using the argument show.legend = FALSE. For example:

ggplot(ToothGrowth, aes(x = dose, y = len))+ 
  geom_boxplot(aes(fill = dose), show.legend = FALSE) +
  scale_fill_viridis_d()

After the plot creation, it’s possible to remove the legend as follow:

p + theme(legend.position = "none")

Remove legend for a particular aesthetic

  1. Create a scatter plot with multiple aesthetics (guides)
# Data preparation
mtcars$cyl<-as.factor(mtcars$cyl)
mtcars$gear <- as.factor(mtcars$gear)

# Scatter plot
p2 <- ggplot(data = mtcars, aes(x = mpg, y = wt))+
    geom_point(aes(color = cyl, size = qsec, shape = gear)) +
  scale_color_viridis_d()
p2

  1. Remove legends for a particular aesthetic (color and size):
p2 + guides(color = FALSE, size = FALSE)



Version: Français





No Comments

Give a comment

Want to post an issue with R? If yes, please make sure you have read this: How to Include Reproducible R Script Examples in Datanovia Comments