Skip to content

Instantly share code, notes, and snippets.

@jennybc
Created October 10, 2014 01:06
Show Gist options
  • Select an option

  • Save jennybc/6f3fa527b915b920fdd5 to your computer and use it in GitHub Desktop.

Select an option

Save jennybc/6f3fa527b915b920fdd5 to your computer and use it in GitHub Desktop.
Reverse the order of a categorical axis in ggplot2
scale_x_discrete(limits = rev(levels(the_factor)))
@davidroberson

Copy link
Copy Markdown

thanks this was very helpful. I found this via a google search.

@bck243

bck243 commented May 18, 2017

Copy link
Copy Markdown

So helpful!!

@yfarjoun

yfarjoun commented Apr 8, 2018

Copy link
Copy Markdown

@zammyfh

zammyfh commented Aug 23, 2018

Copy link
Copy Markdown

Amazing, thank you!

@mgei

mgei commented Sep 18, 2018

Copy link
Copy Markdown

You can also just specify it in the aesthetics
aes(x = reorder(the_factor, desc(the_factor)), ...)

@saskiakess

Copy link
Copy Markdown

Thank you!

@jgarces02

Copy link
Copy Markdown

Thanks a lot!

@ptompalski

Copy link
Copy Markdown

@mgei 's method is slightly better as it works with a faceted graph and scales="free".

@novellisa

Copy link
Copy Markdown

Thank you!

@DohaNaga

Copy link
Copy Markdown

perfecttt!!!

@ibarraespinosa

Copy link
Copy Markdown

so simple, many thanks

@jzadra

jzadra commented May 5, 2020

Copy link
Copy Markdown

unfortunately this does not work with rlang/purrr functional programming:

scale_x_discrete(limits = rev(levels(!!sym(the_factor))))

Error in !sym(the_factor) : invalid argument type

And, as an aside, it does not work if the variable is a character vector rather than a factor (though of course that's an easy fix).

@jennybc

jennybc commented May 5, 2020

Copy link
Copy Markdown
Author

@jzadra The constructs like !! are specific to tidyeval functions, which does not include base functions like levels().

@jzadra

jzadra commented May 5, 2020

Copy link
Copy Markdown

Thanks. It's too bad that the scale_*_reverse() only works on numeric; it seems like it would be useful to have it perform this behavior on factor and character.

@casa-henrym

Copy link
Copy Markdown

This works now: scale_x_discrete(limits = rev)

@ckm2016

ckm2016 commented Oct 16, 2020

Copy link
Copy Markdown

This works now: scale_x_discrete(limits = rev)

Thanks for this!

@AOurednikSFA

Copy link
Copy Markdown

This works now: scale_x_discrete(limits = rev)

Yes, this works! Many thanks

@tnat1031

Copy link
Copy Markdown

this helped me too, thanks!

@ficrawford

Copy link
Copy Markdown

Still helpful in 2024!!! Thanks so much :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment