12.5 C
London
Sunday, July 7, 2024
HomeTidyverse in Rggplot2 in RHow to Remove a Legend Title in ggplot2

How to Remove a Legend Title in ggplot2

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 remove a legend title from a plot in ggplot2:

ggplot(df, aes(x=x_var, y=y_var, color=group_var)) +
  geom_point() +
  labs(color=NULL)

The argument color=NULL in the labs() function tells ggplot2 not to display any legend title.

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

Example: Remove Legend Title from Plot in ggplot2

Suppose we have the following data frame in R that contains information about various basketball players:

df frame(assists=c(3, 4, 4, 3, 1, 5, 6, 7, 9),
                 points=c(14, 8, 8, 16, 3, 7, 17, 22, 26),
                 position=rep(c('Guard', 'Forward', 'Center'), times=3))

#view data frame
df

  assists points position
1       3     14    Guard
2       4      8  Forward
3       4      8   Center
4       3     16    Guard
5       1      3  Forward
6       5      7   Center
7       6     17    Guard
8       7     22  Forward
9       9     26   Center

If we use geom_point() to create a scatterplot in ggplot2, a legend will be shown with a title by default:

library(ggplot2)

#create scatter plot of assists vs. points, grouped by position
ggplot(df, aes(x=assists, y=points, color=position)) +
  geom_point(size=3)

Notice that the legend currently has the text “position” shown as the legend title.

To remove this title from the legend, we can use the labs(color=NULL) argument:

library(ggplot2)

#create scatter plot and remove legend title
ggplot(df, aes(x=assists, y=points, color=position)) +
  geom_point(size=3) +
  labs(color=NULL)

Notice that the legend title has been removed.

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 Size in ggplot2
How to Change Legend Position 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