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

前端 未结 2 1764
长发绾君心
长发绾君心 2020-12-28 08:05

Basically I\'d like to create the first plot shown below in R using ggplot, but with both objects on the same graph (no facet wrapping).

Consider a minimal example

相关标签:
2条回答
  • 2020-12-28 08:34

    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

    0 讨论(0)
  • 2020-12-28 08:39

    You could paste rep and variable a group:

    ggplot(dat) + geom_line(aes(x, value, group = paste(variable, rep), color = variable), 
                        alpha = 0.3) 
    
    0 讨论(0)
提交回复
热议问题