Leila Al
Leila Al

Reputation: 1

Creating a stacked-grouped barplot with different categories per bar ggplot?

I have four variables: categories, x, y and z. X axis should be categories and there should be two bars per category, with the first one being x stacked on top of z, and the second one being y stacked on top of z. It should look like the image linked here (z is blue):

sampledata <- data.frame(
  categories = c("2017", "2018", "2019", "2020"),
  x = c(2, 3, 0, 4),
  y = c(0, 2, 1, 4),
  z = c(1, 0 ,2 ,3)
)

Upvotes: 0

Views: 289

Answers (1)

Matthew Farant
Matthew Farant

Reputation: 82

Technically, there is no way to directly combine stacked and dodged style in geom_bar. But maybe you can do this trick:

#Your data frame
sampledata <- data.frame(
  categories = c("2017", "2018", "2019", "2020"),
  x = c(2, 3, 0, 4),
  y = c(0, 2, 1, 4),
  z = c(1, 0 ,2 ,3)
)
#Reshape into tidy data
library(tidyverse)
sampledata2<-sampledata %>% 
  gather('x','y','z',key='variable',value='value')%>%
  mutate(group=ifelse(variable=='y','b','a')) #group into 2 groups (xz and yz)
sampledata2[13:16,]<-sampledata2[9:12,]
sampledata2[13:16,4]<-c('b','b','b','b')
sampledataA<-sampledata2 %>% 
  filter(group=='a')
sampledataB<-sampledata2 %>% 
  filter(group=='b')
#plot
barwidth=0.30
ggplot()+
#geom_bar for x and z
  geom_bar(data=sampledataA,
          mapping=aes(fill=variable,y=value,x=categories),
          position="stack", 
          stat="identity",
          width=barwidth)+
#geom_bar for y and z
geom_bar(data=sampledataB,
          mapping=aes(x=as.numeric(categories)+barwidth+0.1,fill=variable,y=value),
          position="stack", 
          stat="identity",
          width=barwidth)

more information if it doesn't work: https://community.rstudio.com/t/ggplot-position-dodge-with-position-stack/16425

Upvotes: 1

Related Questions