2016-04-26 107 views
2

一個類別考慮這個最低工作例如:繪製時間序列,其中顏色依賴於與ggplot

library(ggplot2) 
x <- c(1,2,3,4,5,6) 
y <- c(3,2,5,1,3,1) 
data <- data.frame(x,y) 
pClass <- c(0,1,1,2,2,0) 

plottedGraph <- ggplot(data, aes(x = x, y = y, colour = factor(pClass))) + geom_line() 
print(plottedGraph) 

我有一個時間序列Y = F(x),其中x是一個時間步長。每個時間步的顏色應該取決於時間步的類別,記錄在pClass中。

這是它給出結果:

enter image description here

它沒有任何形式的意義,我爲什麼會ggplot具有相同顏色的連接點在一起,而不是遵循相互點(其中根據文件應該做什麼geom_line)。

我如何讓它繪製如下:

enter image description here

回答

6

您應該使用group = 1aes()裏面告訴ggplot,事實上,不同的顏色屬於同一行(即組)。

ggplot(data, aes(x = x, y = y, colour = factor(pClass), group = 1)) + 
    geom_line() 

enter image description here