Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in R Programming by (7.3k points)

Suppose I have a ggplot with more than one legend.

mov <- subset(movies, length != "")

(p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +

  geom_point()

)

I can turn off the display of all the legends like this:

(p1 <- p0 + theme(legend.position = "none"))

Passing show_guide = FALSE to geom_point turns off the shape legend.

(p2 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +

  geom_point(show_guide = FALSE)

)

But what if I want to turn off the color legend instead? There doesn't seem to be a way of telling show_guide which legend to apply its behavior to. And there is no show_guide argument for scales or aesthetics.

(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +

  scale_colour_discrete(show_guide = FALSE) +

  geom_point()

)

# Error in discrete_scale

(p4 <- ggplot(mov, aes(year, rating, shape = mpaa)) +

  aes(colour = length, show_guide = FALSE) +

  geom_point()

)

#draws both legends

I want to be able to do something like

p0 + guides(

  colour = guide_legend(show = FALSE) 

)

but guide_legend doesn't have a show argument.

How do I specify which legends get displayed?

1 Answer

0 votes
by
edited

To turn off legend for a specific aesthetic, you can use the guides() function as follows:

guides(color = FALSE)        #To turn off color legend

guides(fill = FALSE) #To turn off fill legend

guides(shape = FALSE) #To turn off shape legend

Or you can also use scale_color_continuous(guide = FALSE) to suppress the color legend since the length is a continuous variable.

For example:

Plot with all legends:

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 color 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(color = FALSE)

If you want to explore more in R programming then watch this R programming tutorial for beginner:

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...