Change layers order in GG-plot

I am trying to plot scatter plot and color specific dots.
The problem is that the colored dots appear in the lower layer instead of the upper.
how can I change the layers order?

ggplot(my_df) +
geom_point(aes(colour = my_df$a == "11", x = my_df$b, y = my_df$c)) +
scale_colour_manual(values = c("azure3", "blue")) +
scale_size_manual(values =c(1, 5))+
theme(legend.position = "none")

Hi,

Points in the geom_point() function are plotted in order they appear in the dataset. To ensure that your blue-colored points appear on top, you can simply sort the dataset so that the points with the blue label at all in the end. Here is an example:

library("ggplot2")
library("dplyr")

my_df = data.frame(b = runif(1:100), c = runif(1:100), a = "00", stringsAsFactors = F)
my_df$a[sample(1:100, 8)] = "11"

ggplot(my_df %>% arrange(a)) +
  geom_point(aes(x = b, y = c, color = a), size = 10) +
  scale_colour_manual(values = c("azure3", "blue")) +
  scale_size_manual(values =c(1, 5))+
  theme(legend.position = "none")

Alternatively, you could make the plot a bit come complex by separating the blue points to a different layer and plotting them after the azure points, as ggplot evaluated the layers in order they are put in the code:

ggplot(my_df %>% filter(a != "11")) +
  geom_point(aes(x = b, y = c), size = 10, color = "azure3") +
  geom_point(data = my_df %>% filter(a == "11"), aes(x = b, y = c), size = 10, color = "blue")+
  scale_size_manual(values =c(1, 5))+
  theme(legend.position = "none")

Hope this helps,
PJ

2 Likes

Amazing! Thank you!!!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.