2017-04-25 73 views
1

我相當肯定我已經看到了這個地方的解決方案,但由於我一直無法找到它,這裏是我的問題。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) 

我在繪圖

library(ggplot2) 

ggplot(df) + 
    geom_line(aes(x=date,y=temp,colour=factor(location), group=interaction(location,id))) 

使用此代碼它只被定位着色的嘗試。我想要根據位置和ID對線條進行着色。

+1

'ggplot(DF,AES(as.Date(日期),溫度,顏色= ID,線型=位置))+ geom_path()'?或者'ggplot(df,aes(as.Date(date),temp,color = id:location))+ geom_line()',但這樣會讓讀者感到困惑。 – alistaire

回答

4

兩個選項:

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()