11.1 C
London
Sunday, July 7, 2024
HomeTidyverse in Rggplot2 in RHow to Change Legend Labels in ggplot2 (With Examples)

How to Change Legend Labels in ggplot2 (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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 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 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 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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories