Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change alpha level of geom_point in legend on top of stat_smooth

Tags:

r

ggplot2

I'm running into trouble changing the alpha of my (coloured) points in the legend when I add stat_smooth.

require(ggplot2)

set.seed(1052)
dx <- runif(2000,0,10)
dy <- dx * rep(c(1,-1), each = 1000) + rnorm(2000,0,1)
dcol <- rep(c(TRUE, FALSE), each = 1000)
dd <- data.frame(x = dx, y = dy, col = dcol)

gg <- ggplot(dd) + aes(x = x, y = y, colour = col) + geom_point(alpha = 1/5)
gg

The legend is cloudy.

The alpha of the points carries over to the legend (making the colours hard to view), but this question shows that you can override legend details with guides:

magic <- guides(colour = guide_legend(override.aes = list(alpha = 1))) 
gg + magic

It's fixed!

Cool. But when I throw in stat_smooth, the magic stops working.

gg + stat_smooth(method = "lm")

Line is solid, but point has low alpha.

gg + stat_smooth(method = "lm") + magic

I don't know what happened here.

How can I fix this? I would rather have the below result for the legend (white background, line and point with alpha = 1. (The issues seems to go away if you use geom_line and not stat_smooth)

gg + geom_line(alpha = 1/10) + magic

Huh.

like image 772
Blue Magister Avatar asked Sep 26 '13 15:09

Blue Magister


1 Answers

If you want to get legend key with just line and point and without background then you can add fill=NA inside the override.aes= - this will remove grey fill of legend key that is set due to confidence intervals of stat_smooth() (se=TRUE). Then with theme() and legend.key= you can change background to white.

ggplot(dd, aes(x = x, y = y, colour = col)) + geom_point(alpha = 1/5)+
  stat_smooth(method = "lm")+
  guides(colour = guide_legend(override.aes = list(alpha = 1,fill=NA))) + 
  theme(legend.key=element_rect(fill="white"))

enter image description here

like image 55
Didzis Elferts Avatar answered Sep 30 '22 06:09

Didzis Elferts