【问题标题】:Can I reorder the stacking in a geom_col to match the order in my data?我可以重新排序 geom_col 中的堆叠以匹配我的数据中的顺序吗?
【发布时间】:2021-09-17 16:47:00
【问题描述】:

我正在尝试用 ggplot 绘制土壤剖面。但是,geom_col 首先将所有沙层组合在一起,然后是所有泥炭层,最后是所有粘土层。我希望订单取决于我的数据框中的订单,或者取决于 depth_min 的订单。所以第一个剖面是沙-粘土-泥炭-沙子,最后一个是泥炭-花萼-泥炭。 我尝试过使用顺序作为一种美学,但这似乎已被弃用并在网上广泛搜索,但只提出了许多关于颠倒堆栈顺序或更改 de legend 顺序的帖子。有什么解决办法吗?或者也许我不应该(ab)为此使用geom_col,而是使用其他一些功能(最好是ggplot)?

可重现的例子:


d <- read.csv(text='Location,depth_min,depth_max, depth,soil
            1,0,20,20,sand
            1,20,30,10,clay
            1,30,60,30,peat
            1,60,100,40,sand
            2,0,30,30,clay
            2,30,90,60,peat
            3,0,40,40,peat
            3,40,70,30,clay
            3,70,120,50,peat',header=T)

d %>%
  ggplot(aes(x=Location,y=depth, fill = soil)) +
  geom_col(position="stack") +
  scale_y_reverse() +
  theme_bw()

【问题讨论】:

    标签: r ggplot2 stacked-chart


    【解决方案1】:

    实现您想要的结果的一个选项是为您的数据添加一个索引或顺序列,这些列可以映射到group 美学上,以便按照您想要的顺序堆叠您的数据:

    library(dplyr)
    library(ggplot2)
    
    d %>%
      group_by(Location) %>% 
      mutate(order = row_number()) %>% 
      ggplot(aes(x=Location,y=depth, fill = soil, group = order)) +
      geom_col(position="stack") +
      scale_y_reverse() +
      theme_bw()
    

    【讨论】:

      【解决方案2】:

      尝试使用geom_segment() 而不是geom_col()。这是一个可以让您更接近您正在寻找的示例的示例:

      d %>%
        ggplot() +
        geom_segment(aes(x = Location, 
                         xend = Location, 
                         y = depth_min, 
                         yend = depth_max, 
                         colour = soil), 
                     size = 2) +
        scale_y_reverse()
      

      【讨论】:

      • 这确实是 st​​efan 答案的一个非常好的替代方案,感谢 Christopher。可惜我不能接受两个答案!
      【解决方案3】:

      排序/控制堆叠的一种方法是将您的填充变量强制转换为向量并按照您想要的顺序定义级别。

      library(dplyr)
      library(ggplot2)
      
      # check what the following delivers
      d %>% mutate(soil2 = factor(soil, levels = c("peat","clay","sand"))) %>% pull(soil2)
      

      这为您提供了定义排序的因素

      [1] sand clay peat sand clay peat peat clay peat
      Levels: peat clay sand
      

      假设这是我们想要的,我们可以将其注入 ggplot。 ggplot 将根据因子水平进行排序。

      d %>% 
        mutate(soil2 = factor(soil, levels = c("peat","clay","sand"))) %>%
          ggplot(aes(x=Location,y=depth, fill = soil2)) +
          geom_col(position="stack") +
          theme_bw()
      

      瞧:

      尝试改变因子水平的顺序,看看这如何影响堆栈顺序。

      如果您想拆分填充,您需要引入一个单独的变量 for 并将其提供给上面列出的组美学。

      【讨论】:

      • 感谢您的努力,但这不是我的问题的好答案,它以固定顺序排列因子的水平。就我而言(土壤剖面),顺序应取决于数据(或深度)。
      猜你喜欢
      • 2014-08-17
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多