ggplot 因子的反向轴顺序

sta*_*tor 2 r ggplot2 ggridges

这是基础图,从下到上按月份排序,从一到十二个月。我想从上到下订购一到十二个。

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

捕获.png

这两种解决方案都会产生错误。什么是正确的解决方案?

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

错误:提供给连续刻度的离散值。另外:警告消息:1:在 Ops.factor(x) 中:“-”对因子没有意义。2:变换在连续 y 轴上引入了无限值。

并且

# 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))))
Run Code Online (Sandbox Code Playgroud)

is.factor(x) 中的错误:找不到对象“月”

Tho*_*or6 7

尝试 scale_y_discrete(limits = rev)