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

Advertisements

I am trying to make a geom_density_ridges_gradient() graph in R, and want to order the y-axis in chronological order of release (a separate variable in my dataframe). How can I edit my ggplot() command to make this happen? Here is what I currently have, and attached is the output. Or, for simplicity sake, how can I manually order the y-axis categories?

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

>Solution :

If the column in ts by which you would like to order y is called release_date, you can try reorder(), with 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")

While no data were provided, we can see this in action here:

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")
)

Leave a ReplyCancel reply