Search code examples
rggplot2ggridges

ggplot reverse axis order for factors


This is the base plot, with months ordered bottom-to-top one through twelve. I want to order them top-to-bottom one through twelve.

library(tidyverse)
library(nycflights13)
library(ggridges)
ggplot(weather %>% filter(temp > 50), aes(x = temp, y = as.factor(month))) + 
  geom_density_ridges()

Capture.png

Both of these solutions yield errors. What is the correct solution?

# BROKEN SOLUTION 1    
ggplot(weather %>% filter(temp > 50), aes(x = temp, y = as.factor(month))) + 
  geom_density_ridges() + 
  scale_y_continuous(trans = "reverse")

Error: Discrete value supplied to continuous scale. In addition: Warning messages: 1: In Ops.factor(x) : ‘-’ not meaningful for factors. 2: Transformation introduced infinite values in continuous y-axis.

and also

# BROKEN SOLUTION 2
ggplot(weather %>% filter(temp > 50), aes(x = temp, y = as.factor(month))) + 
  geom_density_ridges() + 
  scale_y_discrete(limits = rev(levels(as.factor(month))))

Error in is.factor(x) : object 'month' not found


Solution

  • Try scale_y_discrete(limits = rev)