ggplot2 offset scatterplot points

Viewed 14873

I have two sets of points with error bars. I would like to offset the second so it's displayed slightly down from the first set, so that it doesn't obscure the original.

Here is a mock data set:

x=runif(4,-2,2)
y=c("A","B","C","D")
upper=x+2
lower=x-2
x_1=runif(4,-1,3)
upper_1=x_1+1
lower_1=x_1-2

Here is the code that I used to produce the plot:

qplot(x,y)+
  geom_point(size=6)+
  geom_errorbarh(aes(xmax=upper,xmin=lower),size=1)+
  geom_point(aes(x_1,y),size=6,pch=8,vjust=-1,col="grey40")+
  geom_errorbarh(aes(xmax=upper_1,xmin=lower_1),size=1,col="grey40")

And here is the plot:

scatterplot

I would like the grey asterisks and associated errors bars to be plotted a hair below the black circles and associated error bars. I would transform the data set, but the Y-axis is categorical variables.

4 Answers

In most recent ggplot2, you can set the desired dodge width to match the width of the error bar tails using position = position_dodge(width = #):

set.seed(45)
data <- data.frame(group = c(rep("Z", 4), rep("Y", 4)),
                   value = runif(8),
                   x = rep(c("a","b","c","d"),2))

data$ll <- data$value - abs(runif(8))
data$ul <- data$value + abs(runif(8))


ggplot(data = data, aes(x = x, y = value, color = group)) +
  geom_point(size = 2, position = position_dodge(width = 0.2)) + 
  geom_hline(yintercept = 1, linetype = "dotted") +
  geom_errorbar(aes(ymin = ll, ymax = ul), width = 0.2, position = "dodge")

enter image description here

Related