Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)
edited by

I'm trying to keep the legend of one layer (smooth) and remove the legend of the other (point). I have tried shutting off the legends with guides(colour = FALSE) and geom_point(aes(color = vs), show.legend = FALSE).

Edit: As this question and its answers are popular, a reproducible example seems in order:

library(ggplot2)

ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) +

geom_point(aes(color = vs)) +

geom_point(aes(shape = factor(cyl))) +

geom_line(aes(linetype = factor(gear))) +

geom_smooth(aes(fill = factor(gear), color = gear)) + 

theme_bw() 

enter image description here

1 Answer

0 votes
by
edited by

To remove the legend for a particular aesthetic, add the following functions to your plot:

guides( fill = FALSE)     #To remove legend for fill aesthetic

guides( color = FALSE)    #To remove legend for color aesthetic

guides( shape = FALSE)   #To remove legend for shape aesthetic

theme(legend.position = “none”)      #To remove all legends

For example:

Plot with all legends:

library("ggplot2")

ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) + geom_point(aes(color = vs)) + geom_point(aes(shape = factor(cyl))) + geom_line(aes(linetype = factor(gear))) + geom_smooth(aes(fill = factor(gear), color = gear)) + theme_bw()

Plot without the shape legend:

ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) + geom_point(aes(color = vs)) + geom_point(aes(shape = factor(cyl))) + geom_line(aes(linetype = factor(gear))) + geom_smooth(aes(fill = factor(gear), color = gear)) + theme_bw() + guides(shape = FALSE)

Plot without any legend:

ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) +

  geom_point(aes(color = vs)) +

  geom_point(aes(shape = factor(cyl))) +

  geom_line(aes(linetype = factor(gear))) +

  geom_smooth(aes(fill = factor(gear), color = gear)) +

  theme_bw() +

  theme(legend.position = "none") 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...