How to control which of the factors is calculated first in 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

Here you can see that the points are d2displayed by points d1. So I'm trying to make a difference usingforcats::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

And the d2dots are still on top of the dots d1. Is there a way to change it so that the points d1are on top of the points d2?

+4
source share
1 answer

Just change the sort order so that the points you want on top are in the last rows of the data.

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

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

For other sorting methods see dplyr::arrangeor very fast data.table::setorder.

Another solution, somewhat hacked:

You can simply re-draw your d1 so that they appear on top.

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

Result (anyway)

enter image description here

+3

Source: https://habr.com/ru/post/1690656/


All Articles