Обратный порядок разрывов в ggplot, ggridges

У меня есть набор данных с длиной (целое число) и годом (коэффициент), который я хочу построить, используя ggridges. Вот аналогичный набор данных с целочисленными и факторными данными. Как изменить порядок видов (т. Е. Фактор) по оси 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))

но потом понял, что это для непрерывных переменных (пробовал с годом как числовым - не сработало).


person KVininska    schedule 27.09.2018    source источник


Ответы (1)


Это то, что вы хотите? Я добавил 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

Изменить: еще один более простой способ - использовать fct_rev() из пакета forcats

library(forcats)
library(ggplot2)
library(ggridges)

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

Создано 27.09.2018 с помощью пакета REPEX (v0.2.1.9000)

person Tung    schedule 27.09.2018