How to organize factor levels?

Hi, I usually use some code, for example, to reorder bars in ggplot or other types of sections.

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")

Factor order + ordered schedule

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 very unpleasant for me, and I wonder why arrange()or some other function cannot simplify this. Am I missing something?

Note:

This does not work, but I would like to know if something like this exists in 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")
+4
source share
2 answers

Using < forcats >:

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

Reordering the coefficient using the base:

iris.ba = iris
iris.ba$Species = with(iris.ba, reorder(Species, Sepal.Width, mean))

dplyr:

iris.tr = iris %>% mutate(Species = reorder(Species, Sepal.Width, mean))

, .


: . dplyr mutate. arrange re-order rows, , , ggplot.

. ordered = TRUE , . ordered = TRUE , , "", "", "", , , .

+3

Source: https://habr.com/ru/post/1681627/


All Articles