简体   繁体   中英

r scatter plot with error bars in both directions

How can I create a scatter plot with error bars in two directions? Usually the error bars are in the vertical direction (ie 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

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)

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM