ggplot group by one categorical variable and color by a second one

The problem is that the group aesthetic overrides the standard grouping protocols - it isn't included in the interaction of all discrete variables in the plot described in ?group.

So, to get your plot to work without faceting you would need to manually specify the interaction

ggplot(dat) + geom_line(aes(x, value, group = interaction(rep,variable), color = variable), alpha = 0.3) 

enter image description here

To override the alpha value in the aesthetic, use guide_legend(override.aes = ...)). This information can be found following the links in ?guides and specifically ?guide_legend

eg

ggplot(dat) + geom_line(aes(x, value, group = interaction(rep,variable), color = variable), 
                           alpha = 0.3) + 
  scale_colour_discrete(guide = guide_legend(override.aes = list(alpha = 1)))

enter image description here


You could paste rep and variable a group:

ggplot(dat) + geom_line(aes(x, value, group = paste(variable, rep), color = variable), 
                    alpha = 0.3) 

Tags:

R

Ggplot2