简体   繁体   English

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

[英]How to remove NA value from the plot with ggplot?

I Have data.frame A (3 columns: x,value and SD) with NA value for the same row of the three columns. 我有data.frame A (3列:x,value和SD),其中NA值对应于三列的同一行。 I plot in ggplot with standard deviation (SD), the code is: 我在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"))

the results is: 结果是: 在此处输入图片说明

I would not plot the NA value (in the above plot the gray square with black line), how I can do it? 我不会绘制NA值(在上面绘制带有黑色线条的灰色正方形),我该怎么做? I need plot subset of my df A ? 我需要df A情节子集吗? Thank you 谢谢

Here are two options for plotting gaps: 这是两个绘制间隙的选项:

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

First some example data 首先是一些示例数据

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

If I understand your question, you more or less had the answer. 如果我理解您的问题,您或多或少都有答案。 Just change na.rm to FALSE 只需将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"))

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM