Add error bars to multiple lines to show standard deviation on a plot in R

大城市里の小女人 提交于 2020-01-15 06:08:54

问题


I have a plot with many diferent lines and I'd like to add error bars to each point on every line.

df <- matrix(runif(25),5,5)
plot(1:5,seq(0,1,1/4),type = 'n')
mapply(lines,as.data.frame(df),col=cols,pch=1:5,type="o")

I have tried to use the arrows function but with no success.

stdev <- matrix(runif(25,0,0.1),5,5)
A <- as.data.frame(df) + as.data.frame(stdev)
B <- as.data.frame(df) - as.data.frame(stdev)
mapply(arrows(1:5,A,1:5,B,col=cols,angle=90,length=0.03, code=3))

Any suggestions?


回答1:


arrows is a vectorized function. So there is a possibility to avoid mapply call. Consider (I have also replaced your first mapply call by matplot):

## generate example data
set.seed(0)
mat <- matrix(runif(25), 5, 5)  ## data to plot
stdev <- matrix(runif(25,0,0.1), 5, 5)  ## arbitrary standard error
low <- mat - stdev  ##  lower bound
up <- mat + stdev  ## upper bound

x <- seq(0,1,1/4)  ## x-locations to plot against
## your colour setting; should have `ncol(mat)` colours
## as an example I just use `cols = 1:ncol(mat)`
cols <- 1:ncol(mat)
## plot each column of `mat` one by one (set y-axis limit appropriately)
matplot(x, mat, col = cols, pch = 1:5, type = "o", ylim = c(min(low), max(up)))
xx <- rep.int(x, ncol(mat))  ## recycle `x` for each column of `mat`
repcols <- rep(cols, each = nrow(mat))  ## recycle `col` for each row of `mat`
## adding error bars using vectorization power of `arrow`
arrows(xx, low, xx, up, col = repcols, angle = 90, length = 0.03, code = 3)




回答2:


With ggplot:

set.seed(123) # for reproducibility
data <- as.data.frame(matrix(runif(25),5,5))     # sample data matrix
se <- as.data.frame(matrix(runif(25,0,0.1),5,5)) # SE matrix
data$line <- se$line <- as.factor(1:nrow(data))
library(reshape2)
data <- melt(data, id='line')
se <- melt(se, id='line')
data$ymax <- data$value + se$value
data$ymin <- data$value - se$value
library(ggplot2)
ggplot(data, aes(variable, value, group=line, color=line)) + geom_point() + geom_line() + 
  geom_errorbar(aes(ymax=ymax, ymin=ymin), width=0.25) + xlab('points') 



来源:https://stackoverflow.com/questions/40384055/add-error-bars-to-multiple-lines-to-show-standard-deviation-on-a-plot-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!