ggplot/ggridges 添加层时顺序混乱

ggplot/ggridges order of is mixed up when adding layers

我需要一些帮助。

我正在使用 ggridges,但我遇到了下面举例说明的问题:

我得到一个错误的顺序,即 y 轴的 (1, 10, 11, 2)。我希望最后一个数字的 y 轴顺序为 (1, 2, 3, 10, 20) 代码如下:

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))

# 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))

根据您想要的结果,第二种选择是通过 scale_y_discretelimits 参数设置顺序:

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)))