1

我有一个如下数据集:

dat <- data.frame(sp = c("a", "a", "b", "b", "b", "c", "c"),
nb = c(5, 44, 32, 56, 10, 1, 43),
gp = c("ds1", "ds2", "ds1", "ds2", "ds3", "ds1", "ds3"))

与 sp = 物种 ; nb = nb 次出现;gp = 抽样组

我想制作一个 geom_area 图,其中物种 (sp) 的值显示在 y 轴上,物种在 x 轴上分组,并根据它们的总和按降序排列。

到目前为止,我只设法做到了:

ggplot(dat, aes(x=as.numeric(factor(sp)), y=nb, fill=gp, colour = gp)) +
geom_area()

这给出了这个输出(请不要笑;)) geom_area 的输出

您能帮我按堆叠值总和的降序对 x 轴进行排序吗?并填补空白区域?

例如,我尝试做类似的事情(这里按升序排列,但没关系): 例子

4

1 回答 1

1

尝试这个。可以通过使用gp和的缺失组合填充 df 来填补绘图中的空白。要重新排序我使用的级别:sptidyr::completespforcats::fct_reorder

library(ggplot2)
library(dplyr)
library(tidyr)
library(forcats)

dat <- data.frame(sp = c("a", "a", "b", "b", "b", "c", "c"),
                  nb = c(5, 44, 32, 56, 10, 1, 43),
                  gp = c("ds1", "ds2", "ds1", "ds2", "ds3", "ds1", "ds3"))

dat1 <- dat %>% 
  # Fill with missing combinations of gp and sp
  tidyr::complete(gp, sp, fill = list(nb = 0)) %>% 
  # Reorder according to sum of nb
  mutate(sp = forcats::fct_reorder(sp, nb, sum, .desc = TRUE),
         sp_num = as.numeric(sp))

ggplot(dat1, aes(x=sp_num, y=nb, fill=gp, colour = gp)) +
  geom_area()

于 2020-08-06T15:24:01.037 回答