0

I want to build a graph with ggplot using geom_line. I made up the following reprex to expose the problem:

library(ggplot2)

data <- data.frame(Value = rnorm(20), 
                        Obs = c(1:10,1:10),
                        Var = c(rep("A", 10), rep("B", 10)),
                        Alpha = c(rep(0.7, 10), rep(0.99, 10)))
     
ggplot(data, aes(x = Obs, y = Value, col = Var, alpha = Alpha)) +
       geom_line()

Created on 2020-07-09 by the reprex package (v0.3.0)

I want the "A" variable to be a little bit more transparent than the "B" variable. So I set alpha to 0.7 and 0.99 inside the dataframe for "A" and "B" respectively. However, this produces a plot with "A" much more transparent than "B". In fact, changing alpha to say 0.95 does not change the appearance at all.

I would be very thankful for some guidance.

BerriJ
  • 913
  • 7
  • 18
  • Try `alpha=as.factor(Alpha)`. Or `... + scale_alpha_discrete(...)`. By default, `ggplot` uses a continuous scale for transparency. – Limey Jul 09 '20 at 13:51

2 Answers2

4

You need to add scale_alpha_identity to your plot. This allows the value of Alpha to be interpreted literally as the value of alpha you want for your line:

ggplot(data, aes(x = Obs, y = Value, col = Var, alpha = Alpha)) +
  geom_line() +
  scale_alpha_identity()

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
1

Change your alpha aesthetic to be determined by Var and then use a discrete scale. It will issue a warning because the ggplot2 authors think this is a weird thing to do.

ggplot(data, aes(x = Obs, y = Value, col = Var, alpha = Var)) +
  scale_alpha_discrete(limits = c("A","B"), range = c(0.7, 0.99), guide = FALSE) + 
  geom_line()
Tyler Smith
  • 288
  • 1
  • 7