ggplot中中断的反向顺序,ggridges

时间:2018-09-27 17:58:23

标签: r ggplot2 ggridges

我有一个要使用ggridge绘制的长度(整数)和年份(因子)的数据集。这是具有整数和因子数据的类似数据集。如何更改y轴上物种的顺序(即因子)?

library(ggplot2)
library(ggridges)
library(viridis)
library(datasets)

order <- c("setosa", "versicolor", "virginica")

ggplot(iris, aes(x = Sepal.Length, y = Species, fill = ..x..), order(Species)) + 
  geom_density_ridges_gradient(scale = 3, rel_min_height = 0.01) +
  scale_fill_viridis(name = "Sepal.Length", option = "A") +
  theme_ridges() +
  labs(title = 'Sepal Length distributions for irises')

此处order(Species)order(order)不起作用。

我尝试过:

scale_y_reverse(breaks=order), expand = c(0.01, 0))

,但随后意识到这是用于连续变量的(尝试以年份为数字-无效)。

1 个答案:

答案 0 :(得分:0)

这是您想要的吗?我在您的代码中添加了mutate(Species = factor(Species, levels = rev(myorder)))

library(dplyr)
library(ggplot2)
library(ggridges)
library(viridis)
library(datasets)

myorder <- c("setosa", "versicolor", "virginica")
iris <- iris %>% 
  mutate(Species = factor(Species, levels = rev(myorder)))

ggplot(iris, aes(x = Sepal.Length, y = Species, fill = ..x..), Species) + 
  geom_density_ridges_gradient(scale = 3, rel_min_height = 0.01) +
  scale_fill_viridis(name = "Sepal.Length", option = "A") +
  theme_ridges() +
  labs(title = 'Sepal Length distributions for irises')
#> Picking joint bandwidth of 0.181

reprex package(v0.2.1.9000)于2018-09-27创建