Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

yorder_plot

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading