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()
在这里,您可以看到在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()
并且d2
点仍位于d1
点之上。有没有办法改变它,以便d1
点位于d2
点之上?
答案 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
.
您可以重新绘制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