Как отсортировать бары после группировки top_n в facet_wrap с помощью ggplot2? - PullRequest
1 голос
/ 25 октября 2019

Я сталкиваюсь с проблемой сортировки баров при использовании facet_wrap (о котором обычно сообщают здесь , здесь и другие) после групповых переменных и получения верхних значений. Когда я запускаю код без факторного преобразования, бары упорядочиваются:

iris %>% 
  gather(key = measurements, value = values, - Species) %>% 
  mutate(kk = factor(measurements, levels = unique(.$measurements)),
         species_l = with(., paste(Species, .$measurements, sep = "_"))) %>% 
  ggplot(aes(x = reorder(species_l, values),
             y = values, 
             fill = kk)) +
  geom_bar(stat = "identity") +
  facet_wrap(.~kk,
             scales = "free")

Но теперь я хочу упорядоченно уменьшать бары в пределах facet_wrap и после top_n. Вот то, что я пробовал до сих пор:

library(tidyverse)
iris %>% 
  gather(key = measurements, value = values, - Species) %>% 
  within(., 
         Species <- factor(Species, 
                          levels=names(sort(table(Species), 
                                            decreasing=FALSE)))) %>% 
  ggplot(aes(x = Species,
             y = values, 
             fill = measurements)) +
  geom_bar(stat = "identity") +
  facet_wrap(.~ measurements,
             scales = "free") 

и это:

iris %>% 
  gather(key = measurements, value = values, - Species) %>% 
  group_by(measurements, Species) %>% 
  top_n(5, wt = values) %>% 
  ggplot(aes(x = reorder(Species, Species,
                         function(x)-length(x)),
             y = values, 
             fill = measurements)) +
  geom_bar(stat = "identity") +
  facet_wrap(.~measurements,
             scales = "free")

и это:

iris %>% 
  gather(key = measurements, value = values, - Species) %>% 
  mutate(kk = factor(measurements, levels = unique(.$measurements)),
         species_l = with(., paste(Species, .$measurements, sep = "_"))) %>% 
  group_by(measurements, Species) %>%
  top_n(5, wt = values) %>%
  ungroup() %>%
  ggplot(aes(x = reorder(species_l, values),
             y = values, 
             fill = kk)) +
  geom_bar(stat = "identity") +
  facet_wrap(.~kk,
             scales = "free")

Вот что я получаю: enter image description here

Как видите, Sepal.Width бары не отсортированы.

...