如何控制ggplot2中首先绘制的因子?

时间:2017-12-13 03:17:02

标签: r ggplot2

d1 <- data.frame(x = runif(n = 10000, min = 0, max = 1), y = 
rnorm(10000, sd = 0.2), type = "d1")
d2 <- data.frame(x = runif(n = 10000, min = 0, max = 1), y = 
rnorm(10000, mean = 0.2, sd = 0.2), type = "d2")
all_d <- rbind(d1, d2)
ggplot(all_d, aes(x = x, y = y, color = type)) + geom_point()

enter image description here

在这里,您可以看到在d2点上绘制了d1点。所以我尝试使用forcats::fct_relevel

更改内容
all_d_other <- all_d
all_d_other$type <- forcats::fct_relevel(all_d_other$type, "d2", "d1")
ggplot(all_d_other, aes(x = x, y = y, color = type)) + geom_point()

enter image description here

并且d2点仍位于d1点之上。有没有办法改变它,以便d1点位于d2点之上?

1 个答案:

答案 0 :(得分:3)

只需更改排序顺序,使您想要的点位于数据框的最后一行。

all_d <- all_d[order(all_d$type, decreasing=TRUE),]

ggplot(all_d, aes(x = x, y = y, color = type)) + 
  geom_point()

有关其他排序方式,请参阅dplyr::arrange或非常快data.table::setorder.

另一个解决方案,有点hacky:

您可以重新绘制d1,以便显示在最佳状态。

ggplot(all_d, aes(x = x, y = y, color = type)) + 
  geom_point()+
  geom_point(data=all_d[all_d$type=='d1',]) # re-draw d1's 

结果(无论哪种方式)

enter image description here