ggplot2:如何通过多个变量为图形着色

pha*_*ser 4 r ggplot2

我相当肯定我已经在某处找到了解决方案,但由于我无法找到它,这是我的问题.

我有一些由多个变量识别的时间序列数据,我希望能够使用多个变量来绘制和区分颜色ggplot2.

样本数据:

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 <- data.frame(date,temp,id,location)
Run Code Online (Sandbox Code Playgroud)

我试图绘图

library(ggplot2)

ggplot(df) + 
  geom_line(aes(x=date,y=temp,colour=factor(location), group=interaction(location,id)))
Run Code Online (Sandbox Code Playgroud)

使用此代码只能按位置着色.我希望线条按位置和id着色.

ali*_*ire 11

两种选择:

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
Run Code Online (Sandbox Code Playgroud)

映射id到颜色和location线型:

ggplot(df, aes(date, temp, color = id, linetype = location)) + geom_path()
Run Code Online (Sandbox Code Playgroud)

...或将所有交互作为不同颜色绘制:

ggplot(df, aes(date, temp, color = id:location)) + geom_path()
Run Code Online (Sandbox Code Playgroud)


小智 5

冒号语法对我也不起作用,但这确实有效:

ggplot(df, aes(date, temp, color = interaction(id, location, sep=':'))) + geom_path()