GGPLOT2 : geom_area 以有序字符变量作为 x 轴

GGPLOT2 : geom_area with ordered character variable as x axis

我有如下数据集:

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

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

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

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

试试这个。可以通过使用 tidyr::completegpsp 的缺失组合填充 df 来填补情节中的空白。要重新排序 sp 的级别,我使用 forcats::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()