Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 offset scatterplot points

Tags:

r

offset

ggplot2

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.

like image 550
jslefche Avatar asked Jul 25 '11 16:07

jslefche


People also ask

What does geom_point () do in R?

The function geom_point() adds a layer of points to your plot, which creates a scatterplot.

What is the difference between geom_point and Geom_jitter?

The jitter geom is a convenient shortcut for geom_point(position = "jitter") . It adds a small amount of random variation to the location of each point, and is a useful way of handling overplotting caused by discreteness in smaller datasets.

How do you make a jitter plot in R?

To create a Jitter plot in ggplot2, we can use the geom_jitter method after supplying a continuous variable to the y of our aes , aesthetic. In this example, we will use height from the price data set above. We can also flip the plot to orient horizontally by using the coord_flip method.


1 Answers

Using Richie's reorganization of your data, this is also possible purely within ggplot, without having to mess with the axis:

dodge <- position_dodge(width=0.5)  
p <- ggplot(dfr,aes(x=y,y=x,colour=type)) + 
        geom_point(aes(shape=type),position=dodge) +
        geom_errorbar(aes(ymax=upper,ymin=lower),position = dodge) + 
        scale_colour_manual(values = c('gray','black')) +
        scale_shape_manual(values = c(8,19)) +
        coord_flip() + 
        opts(legend.position="none")

which gives me this plot:

enter image description here

Note: Since version 0.9.2 opts has been replaced by theme:

+ theme(legend.position = "none")
like image 93
joran Avatar answered Nov 02 '22 05:11

joran