2016-04-06 96 views
1

鑑於當NA值不切斷線GGPLOT2:堆疊它們

library(ggplot2) 
df <- data.frame(x=rep(1:5, 2), y=1:10, f=gl(2, 5, labels = letters[1:2])) 
df$y[df$x==3] <- NA 
df 
# x y f 
# 1 1 1 a 
# 2 2 2 a 
# 3 3 NA a 
# 4 4 4 a 
# 5 5 5 a 
# 6 1 6 b 
# 7 2 7 b 
# 8 3 NA b 
# 9 4 9 b 
# 10 5 10 b 

我使用GGPLOT2的默認position_identitygeom_line得到這個數字:

ggplot(df, aes(x, y, color=f)) + 
    geom_line() + 
    geom_point(size=5) 

enter image description here

而且我得到這個數字的時候使用position_stack

ggplot(df, aes(x, y, color=f)) + 
    geom_line(position="stack") + 
    geom_point(size=5, position="stack") 

enter image description here

問:我如何指示NA值使用position_stack的時候,也就是我如何獲得第二個例子中,「洞」?

我的packageVersion("ggplot2")2.1.0。提前致謝。

回答

2

添加明確的group變量...?

df$grp <- c(1,1,NA,2,2,3,3,NA,4,4) 

ggplot(df, aes(x, y, color=f, group = grp)) + 
    geom_line(position="stack") + 
    geom_point(size=5, position="stack") 

當我這樣做,我得到這個:

enter image description here

+0

尼斯,謝謝。我嘗試過'group = f',但那不起作用。 – lukeA