我有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"))
我不会绘制NA值(在上图中用黑线绘制灰色方块),我该怎么做?我需要我的df A
的情节子集?
谢谢
答案 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"))