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?
By specifying legend. position=”none” you're telling ggplot2 to remove all legends from the plot.
Tip: To quickly remove a legend or a legend entry from a chart, you can select it, and then press DELETE. You can also right-click the legend or a legend entry, and then click Delete.
To remove legend title, its legend. title attribute is set to element_blank(). Example: Removing legend title with theme().
You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With