Ben
Ben

Reputation: 6741

How to make graph color depend on two criteria in ggplot2?

Suppose I have a data frame as defined below:

x <- seq(0, 10, by = 0.1)
y1 <- sin(x)
y2 <- cos(x)
y3 <- cos(x + pi / 4)
y4 <- sin(x + pi / 4)
df1 <- data.frame(x, y = y1, Type = as.factor("sin"), Method = as.factor("method1"))
df2 <- data.frame(x, y = y2, Type = as.factor("cos"), Method = as.factor("method1"))
df3 <- data.frame(x, y = y3, Type = as.factor("cos"), Method = as.factor("method2"))
df4 <- data.frame(x, y = y4, Type = as.factor("sin"), Method = as.factor("method2"))

df.merged <- rbind(df1, df2, df3, df4)

So I want to plot the merged data frame and see what is the influence of Type and Method criteria on data. I can of course use colours for Type and line type for Method:

ggplot(df.merged, aes(x, y, colour = Type, linetype = Method)) + geom_line()

But when two curves with the same Type and different Methods are close to each other, it can sometime be hard to distinguish them.

How can I use only colours to distinguish both Type and Method criteria?

Upvotes: 5

Views: 1130

Answers (1)

lukeA
lukeA

Reputation: 54237

You could do

ggplot(df.merged, 
       aes(x, y, colour = interaction(Type, Method))) + 
  geom_line()

enter image description here

Upvotes: 12

Related Questions