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 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
Cool. But when I throw in stat_smooth
, the magic stops working.
gg + stat_smooth(method = "lm")
gg + stat_smooth(method = "lm") + magic
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
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"))
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