Capsicum Capsicum - 4 days ago 6
R Question

R, ggplot2: reverse alphabetical order

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.

Answer

How about:

ggplot(data=dat, aes(x=forcats::fct_rev(reorder(xx,xx)), y=yy))
Comments