rdataframeggplot2dplyrforcats

How to reorder factor levels in a tidy way?


Hi I usually use some code like the following to reorder bars in ggplot or other types of plots.

Normal plot (unordered)

library(tidyverse)
iris.tr <-iris %>% group_by(Species) %>% mutate(mSW = mean(Sepal.Width)) %>%
  select(mSW,Species) %>% 
  distinct()
ggplot(iris.tr,aes(x = Species,y = mSW, color = Species)) +
  geom_point(stat = "identity")

Ordering the factor + ordered plot

iris.tr$Species <- factor(iris.tr$Species,
                          levels = iris.tr[order(iris.tr$mSW),]$Species,
                          ordered = TRUE)
ggplot(iris.tr,aes(x = Species,y = mSW, color = Species)) + 
  geom_point(stat = "identity")

The factor line is extremely unpleasant to me and I wonder why arrange() or some other function can't simplify this. I am missing something?

Note:

This do not work but I would like to know if something like this exists in the tidyverse.

iris.tr <-iris %>% group_by(Species) %>% mutate(mSW = mean(Sepal.Width)) %>%
  select(mSW,Species) %>% 
  distinct() %>% 
  arrange(mSW)
ggplot(iris.tr,aes(x = Species,y = mSW, color = Species)) + 
  geom_point(stat = "identity")

Solution

  • Using ‹forcats›:

    iris.tr %>%
        mutate(Species = fct_reorder(Species, mSW)) %>%
        ggplot() +
        aes(Species, mSW, color = Species) +
        geom_point()