How to Change Legend Labels in ggplot2 (With Examples)


You can use the following syntax to change the legend labels in ggplot2:

p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))

The following example shows how to use this syntax in practice.

Example: Change Legend Labels in ggplot2

Suppose we create the following grouped boxplot in ggplot2:

library(ggplot2) 

#make this example reproducible
set.seed(1)

#create dataset
data <- data.frame(team=rep(c('A', 'B', 'C'), each=50),
                   program=rep(c('low', 'high'), each=25),
                   values=seq(1:150)+sample(1:100, 150, replace=TRUE))

#create grouped boxplots
p <- ggplot(data, aes(x=team, y=values, fill=program)) + 
       geom_boxplot() 

#display grouped boxplots
p

By default, the legend labels take on the following values for the fill variable:

  • high
  • low

However, suppose we’d like to change the legend labels to:

  • High Program
  • Low Program

We can use the following syntax to do so:

#create grouped boxplots with custom legend labels
p <- ggplot(data, aes(x=team, y=values, fill=program)) + 
       geom_boxplot() +
       scale_fill_discrete(labels=c('High Program', 'Low Program'))

#display grouped boxplots
p

The legend now displays the labels that we specified.

Additional Resources

The following tutorials explain how to perform other common tasks in ggplot2:

How to Change the Legend Title in ggplot2
How to Change Legend Position in ggplot2
How to Change Legend Size in ggplot2
How to Remove a Legend in ggplot2

Leave a Reply

Your email address will not be published. Required fields are marked *