如何用ggplot从图中删除NA值?

时间:2016-03-31 09:37:20

标签: r ggplot2 na

我有data.frame A(3列:x,值和SD),其中三列的同一行的NA值。 我用ggplot绘制标准差(SD),代码为:

p <- ggplot(A,aes(x=x,y=value))
p + geom_ribbon(aes(ymin=value-SD,ymax=value+SD),fill = "gray",na.rm=T)+ 
  geom_line(aes(y=value))+
  theme_bw()+ theme(panel.border = element_blank(), panel.grid.major = element_blank(), 
                    panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))

结果是: enter image description here

我不会绘制NA值(在上图中用黑线绘制灰色方块),我该怎么做?我需要我的df A的情节子集? 谢谢

2 个答案:

答案 0 :(得分:2)

以下是绘制差距的两个选项:

# create sample data
set.seed(1)
df <- data.frame(x=1:100, y=runif(100),SD=0.1)
df[45:55, c("x", "y", "SD")] <- NA

# option 1: groupings
ggplot(df, aes(x, y, group=cumsum(is.na(df$x)))) + geom_ribbon(aes(ymin=y-SD,ymax=y+SD),fill = "gray") + geom_line() 

# options 2: interpolations
ggplot(df, aes(zoo::na.approx(x), y)) + geom_ribbon(aes(ymin=y-SD,ymax=y+SD),fill = "gray") + geom_line() 

答案 1 :(得分:1)

首先是一些示例数据

A = data.frame(x = 1900:2000, value=cumsum(rnorm(101)), SD= 0.5)
A[50:60, 2:3] = NA

如果我理解你的问题,你或多或少会得到答案。只需将na.rm更改为FALSE

即可
p = ggplot(A,aes(x=x,y=value))
p + geom_ribbon(aes(ymin=value-SD,ymax=value+SD),fill = "gray",na.rm=FALSE)+ 
  geom_line()+
  theme_bw()+ 
   theme(panel.border = element_blank(), panel.grid.major = element_blank(), 
                    panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))

enter image description here