ggplot2:闪避点与分类轴和重叠点

时间:2018-10-29 22:28:29

标签: r ggplot2 plot graph

考虑下图

d1 = data.frame(x=LETTERS[1:2],y=c(1.9,2.3))
d2 = data.frame(x=LETTERS[1:2],y=c(1.9,3))

ggplot(d1, aes(x=x,y=y)) + geom_point(data=d1, color="red") + 
              geom_point(data=d2, color="blue")

enter image description here

目标是向右闪避蓝色,向左闪避红色点。一种方法是合并两个data.frames

d1$category=1
d2$category=2
d = rbind(d1,d2)
d$category = as.factor(d$category)
ggplot(d, aes(x=x,y=y, color=category)) +
     geom_point(data=d, position=position_dodge(0.3)) + 
      scale_color_manual(values=c("red","blue"))

enter image description here

还有另一种解决方案(不需要合并data.frames的解决方案)吗?

1 个答案:

答案 0 :(得分:1)

您可以使用position_nudge()

library(ggplot2)

d1 <- data.frame(x = LETTERS[1:2], y = c(1.9, 2.3))
d2 <- data.frame(x = LETTERS[1:2], y = c(1.9, 3))

ggplot(d1, aes(x, y)) +
  geom_point(d1, color = "red", position = position_nudge(- 0.05)) +
  geom_point(d2, color = "blue", position = position_nudge(0.05))

enter image description here