将误差线添加到R中的折线图

时间:2017-12-04 22:07:18

标签: r errorbar

我尝试将错误栏添加到以下脚本的折线图中。

#####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坐标上。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

由于您未提供任何样本数据,因此以下是使用某些模拟数据的简单示例。

# 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);

enter image description here

使用ggplot2绘图。

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

enter image description here