我相当确定我已经在某个地方看到了解决方案,但是由于找不到,这是我的问题。
我有一些由多个变量标识的时间序列数据,我希望能够使用中的多个变量来绘制图形并区分颜色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)
我尝试作图
library(ggplot2)
ggplot(df) +
geom_line(aes(x=date,y=temp,colour=factor(location), group=interaction(location,id)))
使用此代码只能按位置着色。我希望线条按位置和ID进行着色。
两种选择:
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
映射id
到颜色和location
线型:
ggplot(df, aes(date, temp, color = id, linetype = location)) + geom_path()
...或将所有互动绘制为不同的颜色:
ggplot(df, aes(date, temp, color = id:location)) + geom_path()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句