R ggplot scatter plot and mean with error bar

2019-08-18 04:23发布

I want to produce a scatter plot and mean value with error bars. My code is as follows. When I add the geom_errorbar(), there is an error message:

Error in FUN(X[[i]], ...) : object 'value' not found

Z <- c(.1,.5,1.)
T <- seq(1:10)
ZT <- expand.grid(Z,T)
colnames(ZT) <- c("Z","T")

n <- nrow(ZT)

nrep <- 100

rmat <- replicate(nrep, rnorm(n))

ave <- apply(rmat,1,mean)
var <- apply(rmat,1,var)
se <- sqrt(var)/sqrt(nrep)

rmat.summary <- as.data.frame(cbind(ZT,ave,se))
colnames(rmat.summary) <- c("Z","T","ave","se") 

library(reshape)
library(ggplot2)


rmat <- as.data.frame(cbind(ZT,rmat))
rmat <- melt(as.data.frame(rmat),id=c(1,2))

ggplot(rmat, aes(x = T, y = value)) + geom_point() + geom_line(data =         
  rmat.summary, aes(x = T, y = ave)) + facet_wrap( ~ Z)

ggplot(rmat, aes(x = T, y = value)) + geom_point() + geom_line(data = 
  rmat.summary, aes(x = T, y = ave)) + 
  geom_errorbar(data = rmat.summary, aes(ymin = ave - se, ymax = ave + se)) 
  + facet_wrap( ~ Z)

So can anybody please help me to correct this error? Thanks in advance!

标签: r ggplot2
1条回答
The star\"
2楼-- · 2019-08-18 04:49

This should work:

ggplot() + 
  geom_point(data = rmat, aes(x = T, y = value)) +
  geom_line(data = rmat.summary, aes(x = T, y = ave)) +
  geom_errorbar(data = rmat.summary, aes(x = T, y = ave, ymin = ave - se, ymax = ave + se)) + 
  facet_wrap( ~ Z)

But I think you have to play around with ymin and ymax.

查看更多
登录 后发表回答