我可以重新排序 geom_col 中的堆叠以匹配我的数据中的顺序吗?

Can I reorder the stacking in a geom_col to match the order in my data?

我正在尝试使用 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()

尝试使用 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()

实现您想要的结果的一个选项是向您的数据添加索引或顺序列,可以映射到 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()

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

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

瞧:

尝试更改因子水平的顺序,看看这对堆栈顺序有何影响。

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