Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change alpha level according to variables

Tags:

r

ggplot2

I have a data frame like this:

dftt <- data.frame(values = runif(11*4,0,1),
                   col = factor(c(rep(2,4),
                           rep(1,4),
                           rep(5,9*4))),
                   x= rep(1:4, 11*4),
                   group=rep(factor(1:11), each=4)
)

I plot it like this

library(ggplot2)
ggplot(dftt, aes(x=x, y=values, group=group, color=col)) + geom_line() 

enter image description here

The blue lines in this plot are just "background" and not as important as red and green, so I want to reduce the alpha level for the blue lines.

I tried this new data frame:

dftt <- data.frame(values = runif(11*4,0,1),
                   col = factor(c(rep(2,4),
                           rep(1,4),
                           rep(5,9*4))),
                   x= rep(1:4, 11*4),
                   group=rep(factor(1:11), each=4),
                   lincol = factor(c(rep(1,9*4), rep(2,2*4)))
)

This data frame has a new variable lincol and I tried to plot it like this:

ggplot(dftt, aes(x=x, y=values, group=group, color=col)) + 
   geom_line(aes(alpha=lincol)) 

But this new plot looks like this:

enter image description here

The alpha is kind of correct but I lost the red and green. Also the legend is weird.

I also want to set the alpha level specifically to 0.5.

like image 428
spore234 Avatar asked Mar 03 '26 08:03

spore234


1 Answers

No need to modify data. Add TRUE/FALSE condition for alpha (alpha = col == 5):

library(ggplot2)
ggplot(dftt, aes(x, values, group = group, color = col, alpha = col == 5)) + 
    geom_line() +
    scale_alpha_manual(values = c(1, 0.5), guide = FALSE)

enter image description here

To set wanted alpha values use scale_alpha_manual and to remove additional legend for alpha use guide = FALSE.


Like this you:

  • Don't have to modify your data
  • Keep same colors
  • Set wanted alpha values
  • Remove unwanted legend
like image 60
pogibas Avatar answered Mar 04 '26 21:03

pogibas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!