【问题标题】:How to sort bars after grouped top_n in facet_wrap with ggplot2?如何使用ggplot2在facet_wrap中对top_n进行分组后对条形进行排序?
【发布时间】:2020-02-22 00:53:51
【问题描述】:

在分组变量后使用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_wraptop_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 条没有排序。

【问题讨论】:

  • @Tung 你可以阅读编辑。我正在尝试重新打开,因为 top_ngroup_modify 似乎标记为重复的答案不适合我的问题。

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


【解决方案1】:

您的第一次尝试很接近 - 您需要确保按方面重新排序,而不仅仅是根据所有测量值的前 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()`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多