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

偶尔善良 提交于 2019-12-05 15:04:07

问题


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?


回答1:


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)) 



回答2:


ggplot2 now includes position_dodge(). From the help's description: "Dodging preserves the vertical position of an geom while adjusting the horizontal position."

Thus you can either use it as geom_point(position = position_dodge(0.5)) or, if you want to dodge points that are connected by lines and need the dodge to the be the same across both geoms, you can use something like:

dat <- data.frame(cond = rep(c("A", "B"), each=10), x=rep(1:10, 2), y=rnorm(20))
dodge <- position_dodge(.3) # how much jitter on the x-axis?
ggplot(dat, aes(x, y, group=cond, color=cond)) + 
  geom_line(position = dodge) + 
  geom_point(position = dodge)


来源:https://stackoverflow.com/questions/31405985/r-how-to-spread-jitter-points-with-respect-to-the-x-axis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!