'ggplot line legend disappears with alpha < 1
When trying to plot some data in ggplot2 using geom_line(), I noticed that the legend items become empty if I use alpha < 1. How can I fix this and why is this happening?
# dummy data
data <- data.frame(
x = rep(1:10, 10),
y = 1:100 + c(runif(50,0,5), runif(50,0,10)),
grp = c(rep("A", 50), rep("B", 50)))
# using alpha on defaul = 1
ggplot(data, aes(x = x, y = y, col = grp)) +
geom_line()
When I plot the same graph, but with alpha < 1, the lines in the legend completely disappear:
# using alpha < 1
ggplot(data, aes(x = x, y = y, col = grp)) +
geom_line(alpha = 0.9)
(versions: R 4.1.3, ggplot2 3.3.5)
Edit: Updating R and restarting RStudio did not help. This also occurs when using R directly without RStudio.
Solution 1:[1]
Legend take the same aes() than plot, you can override this by override.aes.
This should work
ggplot(data, aes(x = x, y = y, col = grp)) +
geom_line(alpha = 0.2) + # using alpha = 0.2 to have it more evident
guides(col = guide_legend(override.aes = list(alpha = 1)))
The same can be used for example to change shape or color of legend elements, respect to aes() mapping in plot
Solution 2:[2]
I ran into the same problem. When saving the plots to PDF/PNG the lines do appear in the legend.
Another workaround I found is adding geom_point() so that way at least you have the colors in the legend:
ggplot(data, aes(x = x, y = y, col = grp)) +
geom_line(alpha = 0.4) +
geom_point(alpha = 0.4, size = 0.1) +
guides(colour = guide_legend(override.aes = list(size=4)))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Svito |
| Solution 2 | Lior |


