Skip to content

Instantly share code, notes, and snippets.

@jennybc
Created October 10, 2014 01:06
Show Gist options
  • Star 35 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jennybc/6f3fa527b915b920fdd5 to your computer and use it in GitHub Desktop.
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)))
@yfarjoun
Copy link

yfarjoun commented Apr 8, 2018

@zammyfh
Copy link

zammyfh commented Aug 23, 2018

Amazing, thank you!

@mgei
Copy link

mgei commented Sep 18, 2018

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

@saskiakess
Copy link

Thank you!

@jgarces02
Copy link

Thanks a lot!

@ptompalski
Copy link

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

@novellisa
Copy link

Thank you!

@DohaNaga
Copy link

perfecttt!!!

@ibarraespinosa
Copy link

so simple, many thanks

@jzadra
Copy link

jzadra commented May 5, 2020

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
Copy link
Author

jennybc commented May 5, 2020

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

@jzadra
Copy link

jzadra commented May 5, 2020

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

This works now: scale_x_discrete(limits = rev)

@ckm2016
Copy link

ckm2016 commented Oct 16, 2020

This works now: scale_x_discrete(limits = rev)

Thanks for this!

@AOurednikSFA
Copy link

This works now: scale_x_discrete(limits = rev)

Yes, this works! Many thanks

@tnat1031
Copy link

this helped me too, thanks!

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