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

前端 未结 5 470
野性不改
野性不改 2020-11-27 03:51

For each X-value I calculated the average Y-value and the standard deviation (sd) of each Y-value

x  = 1:5
y  = c(1.1,         


        
相关标签:
5条回答
  • 2020-11-27 04:24

    You can use segments to add the bars in base graphics. Here epsilon controls the line across the top and bottom of the line.

    plot (x, y, ylim=c(0, 6))
    epsilon = 0.02
    for(i in 1:5) {
        up = y[i] + sd[i]
        low = y[i] - sd[i]
        segments(x[i],low , x[i], up)
        segments(x[i]-epsilon, up , x[i]+epsilon, up)
        segments(x[i]-epsilon, low , x[i]+epsilon, low)
    }
    

    As @thelatemail points out, I should really have used vectorised function calls:

    segments(x, y-sd,x, y+sd)
    epsilon = 0.02
    segments(x-epsilon,y-sd,x+epsilon,y-sd)
    segments(x-epsilon,y+sd,x+epsilon,y+sd)
    

    enter image description here

    0 讨论(0)
  • 2020-11-27 04:25

    A Problem with csgillespie solution appears, when You have an logarithmic X axis. The you will have a different length of the small bars on the right an the left side (the epsilon follows the x-values).

    You should better use the errbar function from the Hmisc package:

    d = data.frame(
      x  = c(1:5)
      , y  = c(1.1, 1.5, 2.9, 3.8, 5.2)
      , sd = c(0.2, 0.3, 0.2, 0.0, 0.4)
    )
    
    ##install.packages("Hmisc", dependencies=T)
    library("Hmisc")
    
    # add error bars (without adjusting yrange)
    plot(d$x, d$y, type="n")
    with (
      data = d
      , expr = errbar(x, y, y+sd, y-sd, add=T, pch=1, cap=.1)
    )
    
    # new plot (adjusts Yrange automatically)
    with (
      data = d
      , expr = errbar(x, y, y+sd, y-sd, add=F, pch=1, cap=.015, log="x")
    )
    
    0 讨论(0)
  • 2020-11-27 04:30

    A solution with ggplot2 :

    qplot(x,y)+geom_errorbar(aes(x=x, ymin=y-sd, ymax=y+sd), width=0.25)
    

    enter image description here

    0 讨论(0)
  • 2020-11-27 04:41

    In addition to @csgillespie's answer, segments is also vectorised to help with this sort of thing:

    plot (x, y, ylim=c(0,6))
    segments(x,y-sd,x,y+sd)
    epsilon <- 0.02
    segments(x-epsilon,y-sd,x+epsilon,y-sd)
    segments(x-epsilon,y+sd,x+epsilon,y+sd)
    

    enter image description here

    0 讨论(0)
  • 2020-11-27 04:42

    You can use arrows:

    arrows(x,y-sd,x,y+sd, code=3, length=0.02, angle = 90)
    
    0 讨论(0)
提交回复
热议问题