rggplot2ggridges

ggplot/ggridges order of is mixed up when adding layers


I am in need of some assistance.

I am using ggridges but I end up with the problem exemplified below:

I get a bad order i.e. (1, 10, 11, 2) of the y axis. I would like the y-axis order of the last figure to be (1, 2, 3, 10, 20) Code below:

library(ggplot2)
library(ggridges)

iris1 <- iris
iris2 <- iris
# change levels 
levels(iris1$Species) <- c(1,2,10)
levels(iris2$Species) <- c(1, 3, 20)
# offset iris2 so we can see it
iris2$Sepal.Length <- iris2$Sepal.Length + 1

# PLots with correct order of y
ggplot() + geom_density_ridges(data = iris1, aes(x = Sepal.Length, y = Species))

enter image description here

# the addition of layers throws off the order
ggplot() + 
  geom_density_ridges(data = iris1, aes(x = Sepal.Length, y = Species)) + 
  geom_density_ridges(data = iris2, aes(x = Sepal.Length, y = Species))

enter image description here


Solution

  • Depending on your desired result a second option would be to set the order via the limits argument of scale_y_discrete:

    library(ggplot2)
    library(ggridges)
    
    ggplot() + 
      geom_density_ridges(data = iris1, aes(x = Sepal.Length, y = Species)) + 
      geom_density_ridges(data = iris2, aes(x = Sepal.Length, y = Species)) +
      scale_y_discrete(limits = as.character(c(1, 2, 3, 10, 20)))