Remove additional legends in ggplot2

I have a simple data frame that I am trying to make using ggplot2 . Suppose my data looks like this:

 df <- data.frame(x=rep(1:10,2), y=c(1:10,11:20), group=c(rep("a",10),rep("b",10))) 

And I'm trying to make a plot:

 g <- ggplot(df, aes(x=x, y=y, group=group)) g <- g + geom_line(aes(colour=group)) g <- g + geom_point(aes(colour=group, alpha = .8)) g 

The result looks great with one exception. It has an extra legend showing alpha for my geom_point layer.

Extra Legend for <code> geom_point </code> transparency

How can I save a legend showing the colors of the group, but not the one that shows my alpha settings?

+72
r ggplot2 legend
Jul 30 '12 at 3:05
source share
3 answers

Aesthetics can be set or displayed in the ggplot call.

  • Aesthetics defined in aes(...) is displayed from the data and a legend is created.
  • Aesthetics can also be set to a single value, defining it outside aes() .

In this case, it looks like you want to set alpha = 0.8 and display colour = group .

To do this,

Put alpha = 0.8 outside the definition of aes() .

 g <- ggplot(df, aes(x = x, y = y, group = group)) g <- g + geom_line(aes(colour = group)) g <- g + geom_point(aes(colour = group), alpha = 0.8) g 

enter image description here

For any displayed variable, you can suppress the legend by using guide = 'none' in the corresponding call to scale_... eg.

 g2 <- ggplot(df, aes(x = x, y = y, group = group)) + geom_line(aes(colour = group)) + geom_point(aes(colour = group, alpha = 0.8)) g2 + scale_alpha(guide = 'none') 

What will return an identical plot

EDIT @Joran's comment in place, I made my answer more comprehensive.

+137
Jul 30 '12 at 3:12
source share

Just add the code show.legend = F after the part where you don't want it.

 g <- ggplot(df, aes(x=x, y=y, group=group)) g <- g + geom_line(aes(colour=group)) g <- g + geom_point(aes(colour=group, alpha = .8), show.legend = F) 
+20
Jan 18 '17 at 15:39
source share

For older versions of ggplot2 (versions prior to 0.9.2 released at the end of 2012), this answer should work:

I tried this with colour_scale and it didn't work. It appears that the colour_scale_hue element works as a function with the default parameter TRUE . I added scale_colour_hue(legend=FALSE) and it worked.

I am not sure if this applies to all color bar elements in ggplot

0
Jan 23 '13 at 15:08
source share



All Articles