Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

r - Remove extra legends in ggplot2

I have a simple data frame that I'm trying to do a combined line and point plot using ggplot2. Supposing 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 fine with one exception. It has an extra legend showing the alpha for my geom_point layer.

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

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Aesthetics can be set or mapped within a ggplot call.

  • An aesthetic defined within aes(...) is mapped from the data, and a legend created.
  • An aesthetic may also be set to a single value, by defining it outside aes().

In this case, it appears you wish to set alpha = 0.8 and map colour = group.

To do this,

Place the alpha = 0.8 outside the aes() definition.

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 mapped variable you can supress the appearance of a legend by using guide = 'none' in the appropriate scale_... call. 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')

Which will return an identical plot

EDIT @Joran's comment is spot-on, I've made my answer more comprehensive


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...