GGPLOT2: geom_area с упорядоченной символьной переменной в качестве оси x - PullRequest
1 голос
/ 06 августа 2020

У меня есть набор данных, подобный следующему:

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

With sp = sizes; nb = nb случаев; gp = sampling group

Я хочу создать график geom_area, на котором значения видов (sp) отображаются по оси y, а виды сгруппированы по оси x и упорядочены по убыванию на основе их общей суммы.

До сих пор мне удавалось сделать только это:

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

Что дает такой результат (пожалуйста, не смейтесь;)) output from geom_area

Could you help me to sort the x axis on descending order of the sum of stacked values ? And to fill the empty area ?

E.g. I try to do something like that (here in ascending order, but it no matters) : пример

1 Ответ

1 голос
/ 06 августа 2020

Попробуйте это. Пробелы в вашем графике можно заполнить, заполнив df недостающими комбинациями gp и sp, используя tidyr::complete. Чтобы изменить порядок уровней 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()

...