0

I use ggplot2 to create a graph using

dat <- data.frame(xx=c("IND","AUS","USA"), yy=c(1,5,2))
ggplot(data=dat, aes(x=reorder(xx,xx), y=yy))

and this nicely sorts my x-axis alphabetically. However, I want to sort the string variable xx in reverse alphabetical order but cannot seem to get it. While reorder(yy,-yy) can sort my numeric variable, reorder(xx,-xx) does not work.

bumblebee
  • 1,116
  • 8
  • 20

1 Answers1

2

How about:

ggplot(data=dat, aes(x=forcats::fct_rev(reorder(xx,xx)), y=yy))
Jacob
  • 3,437
  • 3
  • 18
  • 31
  • 2
    Works! But it appears odd that it requires an additional package. Is there really no solution in base R to reverse-order factors? – bumblebee Nov 29 '16 at 16:09
  • You can do it in base R. Just do it before you plot: `dat$xx <- factor(dat$xx, levels = c(sort(unique(dat$xx), decreasing = TRUE)))` – coip Jan 25 '22 at 18:27