Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Reversed" use of fct_infreq() in ggplot2

Tags:

r

ggplot2

I used fct_infreq() to reorder mpg's model factor levels by frequency. However, the provided code results in a plot where the factor with least counts will appear at the top of the plot. I would like to have it the opposite way, so that the most frequent factor will appear at the top. Is there a way to do that?

ggplot(mpg) + geom_bar(mapping = aes(x = fct_infreq(model))) + coord_flip()

like image 608
J. Doe Avatar asked Oct 22 '18 23:10

J. Doe


1 Answers

ggplot(mpg) +
  geom_bar(mapping = aes(x = fct_rev(fct_infreq(model)))) +
  coord_flip()

enter image description here

BTW, as of ggplot 3.3.0 from March 2020, coord_flip is no longer necessary in most situations -- you can directly map to the axis you want:

ggplot(mpg) +
  geom_bar(mapping = aes(y = fct_rev(fct_infreq(model))))
like image 156
Jon Spring Avatar answered Nov 20 '22 00:11

Jon Spring