ggplot2: how to color a graph by multiple variables
Two options:
library(ggplot2)
df <- data.frame(date = c("2016-04-01 UTC", "2016-05-01 UTC", "2016-06-01 UTC", "2016-04-01 UTC", "2016-05-01 UTC", "2016-06-01 UTC", "2016-04-01 UTC", "2016-05-01 UTC", "2016-06-01 UTC", "2016-04-01 UTC"),
temp = c(80.24018, 85.88911, 104.23125, 85.13571, 91.21129, 104.88333, 97.81116, 107.40484, 121.03958, 87.91830),
id = c("A","A","A","A","A","B","B","B","B","B"),
location = c("N","S","S","N","N","S","N","S","N","S"))
df$date <- as.Date(df$date) # parse dates to get a nicer x-axis
Map id
to color and location
to linetype:
ggplot(df, aes(date, temp, color = id, linetype = location)) + geom_path()
...or plot all interactions as different colors:
ggplot(df, aes(date, temp, color = id:location)) + geom_path()
I want to provide another way of doing that. I don't know why but
color=id:location
doesn't work for me. I solved it by using tidyr::unite
This way I did it:
library(ggplot2)
df <- data.frame(date = c("2016-04-01 UTC", "2016-05-01 UTC", "2016-06-01 UTC", "2016-04-01 UTC", "2016-05-01 UTC", "2016-06-01 UTC", "2016-04-01 UTC", "2016-05-01 UTC", "2016-06-01 UTC", "2016-04-01 UTC"),
temp = c(80.24018, 85.88911, 104.23125, 85.13571, 91.21129, 104.88333, 97.81116, 107.40484, 121.03958, 87.91830),
id = c("A","A","A","A","A","B","B","B","B","B"),
location = c("N","S","S","N","N","S","N","S","N","S"))
df$date <- as.Date(df$date)
df <- tidyr::unite(df,"id_loc",id,location,remove = F)
ggplot(df,aes(date, temp, color = id_loc)) + geom_path()
plot generated