向 R 中的折线图添加误差线

Adding error bars to line graph in R

我正在尝试为以下脚本的折线图添加误差线。

#####Plot FW roses####
ntreatments <- max(df$Treats)

#get the range for the x and y axis
x2range <- range(df$Days)
y2range <- range(df$FWs)

# set up plot
plot(x2range, y2range,
     type = "n",
     xlab= "Time (days)",
     ylab= "Fresh weight (g)")

colors <- c("blue", "red", "black", "darkgreen", "Purple")
linetype <- c(1:ntreatments)
plotchar <- seq(18, 18+ntreatments, 1)


# add lines
for(i in 1:ntreatments) {
  tr2 <- subset(df, Treats==i)
  lines(tr2$Days, tr2$FWs, type="b",
        lwd=1.5,
        lty=linetype[i],
        col=colors[i],
        pch=plotchar[i])
}


# add a title and subtitle
title("Fresh weight")

# add a legend
legend(x2range[1], 
       y2range[2],
       ncol = 2,
       1:ntreatments,
       cex=0.8,
       col=colors,
       pch=plotchar,
       lty=linetype,
       title="Treatment")

我试过了errbar(x2range, y2range, y2range+df$sd, y2range-df$sd)

但结果是所有误差线都聚集在图形的开头和结尾,而不是在相应的 y 坐标上。

我该如何解决这个问题?

由于您没有提供任何示例数据,这里是一个使用一些模拟数据的简单示例。

# Generate some sample data
set.seed(2017);
x <- seq(0, 1, length.out = 10);
y <- 1 + 4 * x + runif(10);
dy <- sqrt(y);
df <- data.frame(x = x, y = y, dy = dy);

以 R 为基数绘图并使用 segments 添加误差线。

# Plot in base R
plot(df$x, df$y, ylim = c(0, 8), type = "l");
segments(df$x, df$y - df$dy, df$x, df$y + df$dy);

或使用 ggplot2.

绘图
# Plot in ggplot
ggplot(df, aes(x = x, y = y)) +
    geom_line() +
    geom_errorbar(aes(ymin = y - dy, ymax = y + dy));