cboettig
cboettig

Reputation: 12677

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

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 that mimics my data structure:

library(reshape2)
library(ggplot2)
x <- seq(1, 5, length = 100)
y <- replicate(10, sin(2 * pi * x) + rnorm(100, 0, 0.3), "list")
z <- replicate(10, sin(2 * pi * x) + rnorm(100, 5, 0.3), "list")
y <- melt(y)
z <- melt(z)
df <- data.frame(x = y$Var1, rep = y$Var2, y = y$value, z = z$value)
dat <- melt(df, id = c("x", "rep"))

I can plot it with

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

And get


(source: carlboettiger.info)

But if I try dropping the facet wrapping, I thought it should group by color and variable, but instead the data are not broken out correctly, resulting in nonsense:


(source: carlboettiger.info)

Upvotes: 23

Views: 61697

Answers (2)

mnel
mnel

Reputation: 115382

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

Upvotes: 37

EDi
EDi

Reputation: 13280

You could paste rep and variable a group:

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

Upvotes: 3

Related Questions