Reputation: 1380
I have a line plot that uses alpha as one of its scales.
Unfortunately, it seems that there is an error which results in alpha legends not working, even if they're working in the plot and Hadley has dismissed it as a Windows error.
As a work around, does anyone know how to change the geom in the legend from being a line to being a box (in the same way the fill of a bar chart would be presented)?
I've fiddled with the overwrite_aes
argument of guide_legend however if that's the solution, I haven't worked out what argument to use.
Sample ggplot:
ggplot(data, aes(x = x)) +
geom_line(aes(y = y1, alpha = "test 1")) +
geom_line(aes(y = y2, alpha = "test 2")) +
scale_alpha_manual(values = c(1, 0.5))
Upvotes: 0
Views: 53
Reputation: 22074
Perhaps it's not perfect, but I found override.aes()
to work.
library(tidyverse)
dat <- tibble(
x = 1:10,
y1 = runif(10),
y2 = runif(10)
)
ggplot(dat, aes(x = x)) +
geom_line(aes(y = y1, alpha = "test 1")) +
geom_line(aes(y = y2, alpha = "test 2")) +
scale_alpha_manual(values = c(1, 0.5)) +
guides(alpha = guide_legend(override.aes = list(size = 6))) +
theme_classic()
Edit: Something "hackier"
This is certainly hackier than the first one.
ggplot() +
geom_line(data=dat, aes(x=x, y = y1), alpha=1) +
geom_line(data=dat, aes(x=x, y = y2), alpha =.5) +
geom_segment(aes(x=min(dat$x), xend=min(dat$x + .05*diff(range(dat$x))),
y = max(c(dat$y1, dat$y2)), yend=max(c(dat$y1, dat$y2))),
alpha=1, size=6) +
geom_segment(aes(x=min(dat$x), xend=min(dat$x + .05*diff(range(dat$x))),
y = max(c(dat$y1, dat$y2))-.025, yend=max(c(dat$y1, dat$y2))-.025),
alpha=.5, size=6) +
geom_text(aes(x=min(dat$x + .06*diff(range(dat$x))),
y = max(c(dat$y1, dat$y2)),
label = "test1"), hjust=0) +
geom_text(aes(x=min(dat$x + .06*diff(range(dat$x))),
y = max(c(dat$y1, dat$y2))-.025,
label = "test2"), hjust=0)+
theme_classic()
Upvotes: 1