在使用ggplot2将facet_wrap中的top_n分组之后,如何对条形进行排序?

时间:2019-10-25 16:32:13

标签: r ggplot2 geom-bar facet-wrap top-n

在分组变量并获得最高值之后使用facet_wrap(通常报告为herehere等)时,我面临排序条的问题。 当我在不进行因子转换的情况下运行代码时,条形排列如下:

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条没有排序。

1 个答案:

答案 0 :(得分:0)

您的首次尝试已接近完成-您需要确保对每个方面进行重新排序,而不仅仅是根据所有测量结果的前5个值对因子进行重新排序。朱莉娅·席尔格(Julia Silge)详尽解释了here

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()`