Reputation: 14136
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.
How can I keep the legend showing group colors, but not the one that shows my alpha settings?
Upvotes: 135
Views: 160223
Reputation: 41563
Another simple option is using the function guides
, which makes it possible to remove a particular aesthetic (fill, alpha, color) or multiple from the legend. Here is a reproducible example for removing only alpha legend and removing both alpha and color:
df <- data.frame(x=rep(1:10,2), y=c(1:10,11:20),
group=c(rep("a",10),rep("b",10)))
library(ggplot2)
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))
# Remove legend alpha
g + guides(alpha = "none")
# Remove legend alpha and color
g + guides(alpha = "none", color = "none")
Created on 2022-08-21 with reprex v2.0.2
Upvotes: 22
Reputation: 859
Just add the show.legend = F
code 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)
Upvotes: 82
Reputation: 11
For old versions of ggplot2 (versions before 0.9.2, released in late 2012), this answer should work:
I tried this with a colour_scale
and it did not work. It appears that the colour_scale_hue
item works like a function with a default parameter TRUE
. I added scale_colour_hue(legend=FALSE)
and it worked.
I am not sure if this is the case for all color scale items in ggplot
Upvotes: 1
Reputation: 115485
Aesthetics can be set or mapped within a ggplot
call.
aes(...)
is mapped from the data, and a legend created.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
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
Upvotes: 241