2016-04-26 52 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