2

How can I create a scatter plot with error bars in two directions? Usually the error bars are in the vertical direction (i.e. the uncertainty in the y value). However my data has uncertainty in the x value as well

X      ErrX   Y     ErrY
1.0    0.1    3.0   0.2
1.5    0.3    4.2   0.1
etc
Alex Lizz
  • 425
  • 1
  • 8
  • 19

3 Answers3

4

Using ggplot2, this is easy. You have complete control over the length of all four "sides" of the errorbars. With geom_errorbar() you set the y-errors, and geom_errobarh() (the h is for horizontal) you set the x-errors.

#toy data
df <- data.frame(X = rnorm(4), errX = rnorm(4)*0.1, Y = rnorm(4), errY = rnorm(4)*0.2)

#load ggplot2
require(ggplot2)

#make graph
ggplot(data = df, aes(x = X, y = Y)) + geom_point() + #main graph
    geom_errorbar(aes(ymin = Y-errY, ymax = Y+errY)) + 
    geom_errorbarh(aes(xmin = X-errX, xmax = X+errX))

You have separate control for the color of each bar, the linewidth, etc by setting parameters inside geom_errorbar(). See the help and Google for details. For example, you can control the width of the "caps" or eliminate them entirely with the width parameter. Compare the graph above to this one for an example of removing them:

ggplot(data = df, aes(x = X, y = Y)) + geom_point() + 
        geom_errorbar(aes(ymin = Y-errY, ymax = Y+errY), width = 0) + 
        geom_errorbarh(aes(xmin = X-errX, xmax = X+errX), height = 0)
Curt F.
  • 4,690
  • 2
  • 22
  • 39
  • 1
    Made several edits to correct typos in my initial writeup. In particular, `geom_errorbarh` controls the "cap length" with the `height` parameter, analogous to the `width` for `geom_errobar`. – Curt F. Feb 15 '15 at 04:22
  • any idea of how caps can be removed only on onw side of the errorbar? – AJMA May 27 '17 at 05:25
1

As an alternative (using Curt F. 's "df"):

rangeX = range(c(df$X + df$errX, df$X - df$errX))
rangeY = range(c(df$Y + df$errY, df$Y - df$errY))

plot(df$X, df$Y, xlim = rangeX, ylim = rangeY)

segments(df$X, df$Y - df$errY, df$X, df$Y + df$errY)
segments(df$X - df$errX, df$Y, df$X + df$errX, df$Y)
alexis_laz
  • 12,884
  • 4
  • 27
  • 37
1

Using error.crosses from my psych package + the toy data from Curt:

 df1 <- data.frame(mean=df$X,sd=df$errX)
 df2 <- data.frame(mean=df$Y,sd=df$errY) 
 error.crosses(df1,df2,sd=TRUE)

See the help page for error.crosses for some more complicated examples.

William Revelle
  • 1,200
  • 8
  • 15