Как отсортировать столбцы после группировки top_n в facet_wrap с помощью ggplot2?

У меня возникла проблема с полосами сортировки при использовании 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")

Вот что я получаю: введите здесь описание изображения

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


person patL    schedule 25.10.2019    source источник
comment
Попробуйте и это, значение в аспектах ggplot"> stackoverflow.com/questions/52214071/   -  person Tung    schedule 25.10.2019
comment
@Tung, ты можешь читать правки. Я пытаюсь снова открыть, так как с top_n и group_modify кажется, что ответы, помеченные как дублированные, не соответствуют моему вопросу.   -  person patL    schedule 30.10.2019


Ответы (1)


Ваша первая попытка была близка — вам нужно убедиться, что вы переупорядочиваете по аспекту, а не просто переупорядочиваете фактор на основе 5 лучших значений всех измерений. Джулия Силге подробно объясняет здесь

library(tidytext) 
library(tidyverse)
library(magtrittr)

iris %>%
   gather(key = measurements, value = values, - Species) %>% 
    mutate(kk = factor(measurements, levels = unique(.$measurements)),
#The '-values' below specifies to order in descending
      Species = reorder_within(Species, -values, measurements)) %>% 
   ggplot(aes(x = Species, y = values, fill = kk)) +
      geom_bar(stat = "identity") +
        facet_wrap(.~kk, scales = "free") +
      scale_x_reordered()`
person Jonni    schedule 15.07.2020