I have a dataset with Length (integer) and Year (factor) that I want to plot using ggridges
. Here is an analogous dataset with integer and factor data. How do I change the order of Species (i.e. factor) on the y-axis?
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')
Here, order(Species)
or order(order)
doesn't work.
I tried:
scale_y_reverse(breaks=order), expand = c(0.01, 0))
but then realized this is for continuous variables (tried with year as numeric - didn't work).
Is this what you want? I added mutate(Species = factor(Species, levels = rev(myorder)))
to your code
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
Edit: another simpler way is to use fct_rev()
from the forcats
package
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
Created on 2018-09-27 by the reprex package (v0.2.1.9000)