带有误差条的散点图

问题描述 投票:42回答:6

如何在R中生成以下图?图中显示的点是平均值,它们的范围对应于最小值和最大值。我有两个文件中的数据(下面是一个例子)。

x   y
1   0.8773
1   0.8722
1   0.8816
1   0.8834
1   0.8759
1   0.8890
1   0.8727
2   0.9047
2   0.9062
2   0.8998
2   0.9044
2   0.8960
..  ...

r plot
6个回答
110
投票

首先:非常不幸和令人惊讶的是R无法“开箱即用”绘制错误条。

这是我最喜欢的解决方法,优点是您不需要任何额外的包。诀窍是绘制箭头(!)但是用小水平条代替箭头(!!!)。这个不那么直截了当的想法来自R Wiki Tips,并在这里作为一个解决的例子再现。

假设你有一个“平均值”avg的矢量和另一个“标准偏差”sdev的矢量,它们具有相同的长度n。让横坐标只是这些“测量”的数量,所以x <- 1:n。使用这些,这里有绘图命令:

plot(x, avg,
    ylim=range(c(avg-sdev, avg+sdev)),
    pch=19, xlab="Measurements", ylab="Mean +/- SD",
    main="Scatter plot with std.dev error bars"
)
# hack: we draw arrows but with very special "arrowheads"
arrows(x, avg-sdev, x, avg+sdev, length=0.05, angle=90, code=3)

结果如下:

arrows(...)函数中,length=0.05是以英寸为单位的“箭头”的大小,angle=90指定“箭头”垂直于箭头的轴,而特别直观的code=3参数指定我们想在两端绘制箭头。箭头。

对于水平误差条,必须进行以下更改,假设sdev向量现在包含x值中的误差,y值为纵坐标:

plot(x, y,
    xlim=range(c(x-sdev, x+sdev)),
    pch=19,...)
# horizontal error bars
arrows(x-sdev, y, x+sdev, y, length=0.05, angle=90, code=3)

8
投票

使用ggplot和一点dplyr进行数据处理:

set.seed(42)
df <- data.frame(x = rep(1:10,each=5), y = rnorm(50))

library(ggplot2)
library(dplyr)

df.summary <- df %>% group_by(x) %>%
    summarize(ymin = min(y),
              ymax = max(y),
              ymean = mean(y))

ggplot(df.summary, aes(x = x, y = ymean)) +
    geom_point(size = 2) +
    geom_errorbar(aes(ymin = ymin, ymax = ymax))

如果有一个额外的分组列(OP的示例图每个x值有两个错误条,说数据来自两个文件),那么你应该在开始时获得一个数据框中的所有数据,将分组变量添加到dplyr::group_by调用(例如,如果group_by(x, file)是列的名称,则为file)并将其添加为ggplot中的“​​组”美学,例如aes(x = x, y = ymean, group = file)


6
投票
#some example data
set.seed(42)
df <- data.frame(x = rep(1:10,each=5), y = rnorm(50))

#calculate mean, min and max for each x-value
library(plyr)
df2 <- ddply(df,.(x),function(df) c(mean=mean(df$y),min=min(df$y),max=max(df$y)))

#plot error bars
library(Hmisc)
with(df2,errbar(x,mean,max,min))
grid(nx=NA,ny=NULL)

3
投票

总结Laryxdecidua回答:

定义并使用如下所示的函数

plot.with.errorbars <- function(x, y, err, ylim=NULL, ...) {
  if (is.null(ylim))
    ylim <- c(min(y-err), max(y+err))
  plot(x, y, ylim=ylim, pch=19, ...)
  arrows(x, y-err, x, y+err, length=0.05, angle=90, code=3)
}

其中一个可以覆盖自动ylim,并传递额外的参数,如main,xlab,ylab。


1
投票

Another (easier - at least for me) way to do this is below.

install.packages("ggplot2movies")

data(movies, package="ggplot2movies")
Plot average Length vs Rating
rating_by_len = tapply(movies$length,
                       movies$rating,
                       mean)

plot(names(rating_by_len), rating_by_len, ylim=c(0, 200)
     ,xlab = "Rating", ylab = "Length", main="Average Rating by Movie Length", pch=21)
Add error bars to the plot: mean - sd, mean + sd
sds = tapply(movies$length, movies$rating, sd)
upper = rating_by_len + sds
lower = rating_by_len - sds
segments(x0=as.numeric(names(rating_by_len)), 
         y0=lower, 
         y1=upper)

希望有所帮助。


-1
投票

我总结了一个假设实验的代码,其中十次测量重复三次。只是为了在其他stackoverflowers的帮助下获得乐趣。谢谢...显然循环是一个选项,因为使用applycan但我喜欢看看会发生什么。

#Create fake data
x <-rep(1:10, each =3)
y <- rnorm(30, mean=4,sd=1)

#Loop to get standard deviation from data
sd.y = NULL
for(i in 1:10){
  sd.y[i] <- sd(y[(1+(i-1)*3):(3+(i-1)*3)])
}
sd.y<-rep(sd.y,each = 3)

#Loop to get mean from data
mean.y = NULL
for(i in 1:10){
  mean.y[i] <- mean(y[(1+(i-1)*3):(3+(i-1)*3)])
}
mean.y<-rep(mean.y,each = 3)

#Put together the data to view it so far
data <- cbind(x, y, mean.y, sd.y)

#Make an empty matrix to fill with shrunk data
data.1 = matrix(data = NA, nrow=10, ncol = 4)
colnames(data.1) <- c("X","Y","MEAN","SD")

#Loop to put data into shrunk format
for(i in 1:10){
  data.1[i,] <- data[(1+(i-1)*3),]
}

#Create atomic vectors for arrows
x <- data.1[,1]
mean.exp <- data.1[,3]
sd.exp <- data.1[,4]

#Plot the data
plot(x, mean.exp, ylim = range(c(mean.exp-sd.exp,mean.exp+sd.exp)))
abline(h = 4)
arrows(x, mean.exp-sd.exp, x, mean.exp+sd.exp, length=0.05, angle=90, code=3)
© www.soinside.com 2019 - 2024. All rights reserved.