如何更改 ggplot2 R 中 y 轴的顺序?

How do I change the order of the y-axis in ggplot2 R?

我正在尝试在 R 中制作一个 geom_density_ridges_gradient() 图,并希望按发布的时间顺序对 y 轴进行排序(我的数据框中的一个单独变量)。如何编辑我的 ggplot() 命令来实现这一点?这是我目前拥有的,附件是输出。或者,为了简单起见,我如何手动对 y 轴类别进行排序?

ggplot(ts, aes(x = danceability, y = album_name)) +
  geom_density_ridges_gradient(scale = .9) +
  theme_light() +
  labs(title = "Danceability by Albums",
       x = "Danceability",
       y = "Album Name")

Plot Output

如果 ts 中您想要订购 y 的列称为 release_date,您可以尝试 reorder(),使用 decreasing=T

ggplot(ts, aes(x = danceability, y = reorder(album_name, release_date,decreasing=T)) +
  geom_density_ridges_gradient(scale = .9) +
  theme_light() +
  labs(title = "Danceability by Albums",
       x = "Danceability",
       y = "Album Name")

虽然没有提供任何数据,但我们可以在这里看到实际情况:

set.seed(123)
data = data.frame(y=rep(letters[1:3],100), x=rnorm(300), o=rep(c(1,3,2),100))

gridExtra::grid.arrange(
  ggplot(data, aes(x,y)) + geom_density_ridges_gradient(scale=0.9) + ggtitle("Unordered"),
  ggplot(data, aes(x,reorder(y,o,decreasing=T))) + geom_density_ridges_gradient(scale=0.9) + ggtitle("Ordered")
)