Подтвердить что ты не робот

Ggplot2 - бар с обоими стопами и уклоном

Я пытаюсь создать barplot, используя ggplot2, где я укладываю одну переменную и уклоняюсь другой.

Вот пример набора данных:

df=data.frame(
  year=rep(c("2010","2011"),each=4),
  treatment=rep(c("Impact","Control")),
  type=rep(c("Phylum1","Phylum2"),each=2),
  total=sample(1:100,8))

Я хотел бы создать barplot, где x=treatment, y=total, уложенная переменная type, а уклоненная переменная year. Конечно, я могу сделать одно или другое:

ggplot(df,aes(y=total,x=treatment,fill=type))+geom_bar(position="dodge",stat="identity")

ggplot(df,aes(y=total,x=treatment,fill=year))+geom_bar(position="dodge",stat="identity")

Но не оба! Спасибо всем, кто может дать совет.

4b9b3361

Ответ 1

Вот альтернативный вариант использования огранки вместо уклонения:

ggplot(df, aes(x = year, y = total, fill = type)) +
    geom_bar(position = "stack", stat = "identity") +
    facet_wrap( ~ treatment)

enter image description here

С Тайлером предложено изменение: + theme(panel.margin = grid::unit(-1.25, "lines"))

enter image description here

Ответ 2

Самое близкое, что вы можете получить, - это рисовать границу вокруг столбцов dodged, чтобы выделить значения type.

ggplot(df, aes(treatment, total, fill = year)) + 
geom_bar(stat="identity", position="dodge", color="black")

enter image description here

Ответ 3

Вы можете использовать interaction(year, treatment) в качестве переменной оси X в качестве альтернативы dodge.

library(tidyverse)

df=data.frame(
  year=rep(c("2010","2011"),each=4),
  treatment=rep(c("Impact","Control")),
  type=rep(c("Phylum1","Phylum2"),each=2),
  total=sample(1:100,8)) %>% 
  mutate(x_label = factor(str_replace(interaction(year, treatment), '\\.', ' / '), ordered=TRUE))

ggplot(df, aes(x=x_label, y=total, fill=type)) +
  geom_bar(stat='identity') + labs(x='Year / Treatment')

Создано в 2018-04-26 пакетом Представитель (v0.2.0).

Ответ 4

Это может быть сделано, однако это сложно/неудобно, вам в основном нужно наложить гистограмму.

вот мой код:

library(tidyverse)

df=data.frame(
  year=rep(c(2010,2011),each=4),
  treatment=rep(c("Impact","Control")),
  type=rep(c("Phylum1","Phylum2"),each=2),
  total=sample(1:100,8))

# separate the by the variable which we are dodging by so 
# we have two data frames impact and control
impact <- df %>% filter(treatment == "Impact") %>% 
  mutate(pos = sum(total, na.rm=T))

control <- df %>% filter(treatment == "Control") %>% 
  mutate(pos = sum(total, na.rm=T))

# calculate the position for the annotation element
impact_an <- impact %>% group_by(year) %>% 
  summarise(
    pos = sum(total) + 12
    , treatment = first(treatment)
  )

control_an <- control %>% group_by(year) %>% 
  summarise(
    pos = sum(total) + 12
    , treatment = first(treatment)
  )

# define the width of the bars, we need this set so that
# we can use it to position the second layer geom_bar 
barwidth = 0.30

ggplot() +
  geom_bar(
    data = impact
    , aes(x = year, y = total, fill = type)
    , position = "stack"
    , stat = "identity"
    , width = barwidth
  ) + 
  annotate(
    "text"
    , x = impact_an$year
    ,y = impact_an$pos
    , angle = 90
    , label = impact_an$treatment
  ) +
  geom_bar(
    data = control
    # here we are offsetting the position of the second layer bar
    # by adding the barwidth plus 0.1 to push it to the right
    , aes(x = year + barwidth + 0.1, y = total, fill = type)
    , position = "stack"
    , stat = "identity"
    , width = barwidth
  ) +
  annotate(
    "text"
    , x = control_an$year + (barwidth * 1) + 0.1
    ,y = control_an$pos
    , angle = 90
    , label = control_an$treatment
  ) +
  scale_x_discrete(limits = c(2010, 2011))

stacked dodged barchar Это не очень хорошо масштабируется, однако есть способы, которыми вы могли бы его кодировать, чтобы он соответствовал вашей ситуации, и это заслуга, когда я должен был изучить этот метод из следующего поста: https://community.rstudio.com/t/ggplot-position-dodge-with-position-stack/16425