Search code examples
rerrorbar

Adding error bars to line graph in R


I'm trying to add error bars to line graphs to the following script.

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

I have tried errbar(x2range, y2range, y2range+df$sd, y2range-df$sd)

But the result is that all errorbars gather at the beginning and the end of the graph and not on the corresponding y coordinates.

How can I solve this?


Solution

  • Since you don't provide any sample data, here is a simple example using some simulated data.

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

    Plot in base R and add error bars using 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

    Or plot using 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