I am making a dodged bar chart using ggplot with discrete x scale, the x axis are now arranged in alphabetical order, but I need to rearrange it so that it is ordered by the
Hadley has been developing a package called forcats
. This package makes the task so much easier. You can exploit fct_infreq()
when you want to change the order of x-axis by the frequency of a factor. In the case of the mtcars
example in this post, you want to reorder levels of cyl
by the frequency of each level. The level which appears most frequently stays on the left side. All you need is the fct_infreq()
.
library(ggplot2)
library(forcats)
ggplot(mtcars, aes(fct_infreq(factor(cyl)))) +
geom_bar() +
labs(x = "cyl")
If you wanna go the other way around, you can use fct_rev()
along with fct_infreq()
.
ggplot(mtcars, aes(fct_rev(fct_infreq(factor(cyl))))) +
geom_bar() +
labs(x = "cyl")