4
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 d2 points are plotted over the d1 points. So I try changing things using 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

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

rmflight
  • 1,871
  • 1
  • 14
  • 22
  • did you try plain base `?relevel`? Worst case, you can add a separate `+geom_point()` for the d1, which will force them to be plotted second (on top) – C8H10N4O2 Dec 13 '17 at 03:21
  • R 3.4.2, ggplot2 2.2.1.9000 – rmflight Dec 13 '17 at 03:30
  • @C8H10N4O2, I didn't try base "relevel", as the "levels" seem to be modified as I expected, and also shown by the change in colors – rmflight Dec 13 '17 at 03:32
  • See https://stackoverflow.com/questions/15706281/controlling-order-of-points-in-ggplot2-in-r, apparently draw order is affected by the current order of your dataframe rather than the factor levels. This probably counts as a dupe of that question. – Marius Dec 13 '17 at 03:34

1 Answers1

4

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

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

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

For other ways to sort, see dplyr::arrange or the very fast data.table::setorder.

Another solution, somewhat hacky:

You can just re-draw your d1's so they show 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's 

Result (either way)

enter image description here

C8H10N4O2
  • 18,312
  • 8
  • 98
  • 134