Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: How to spread (jitter) points with respect to the x axis?

Tags:

r

ggplot2

jitter

I have the following code snippet in R:

dat <- data.frame(cond = factor(rep("A",10)), 
                  rating = c(1,2,3,4,6,6,7,8,9,10))
ggplot(dat, aes(x=cond, y=rating)) +
  geom_boxplot() + 
  guides(fill=FALSE) +
  geom_point(aes(y=3)) +
  geom_point(aes(y=3)) +
  geom_point(aes(y=5))

This particular snippet of code produces a boxplot where one point goes over another (in the above case one point 3 goes over another point 3).

How can I move the point 3 so that the point remains in the same position on the y axis, but it is slightly moved left or right on the x axis?

like image 448
chao Avatar asked Jul 14 '15 12:07

chao


People also ask

What does position jitter do in R?

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.

What is a jitter plot?

A jitter plot represents data points in the form of single dots, in a similar manner to a scatter plot. The difference is that the jitter plot helps visualize the relationship between a measurement variable and a categorical variable.


1 Answers

This can be achieved by using the position_jitter function:

geom_point(aes(y=3), position = position_jitter(w = 0.1, h = 0))

Update: To only plot the three supplied points you can construct a new dataset and plot that:

points_dat <- data.frame(cond = factor(rep("A", 3)), rating = c(3, 3, 5))                  
ggplot(dat, aes(x=cond, y=rating)) +
  geom_boxplot() + 
  guides(fill=FALSE) +
  geom_point(aes(x=cond, y=rating), data = points_dat, position = position_jitter(w = 0.05, h = 0)) 
like image 112
Lars Lau Raket Avatar answered Sep 24 '22 03:09

Lars Lau Raket