0

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)
)
Leila Al
  • 1
  • 1
  • Check this: [How to plot a Stacked and grouped bar chart in ggplot?](https://stackoverflow.com/questions/46597278/how-to-plot-a-stacked-and-grouped-bar-chart-in-ggplot/46597859#46597859) and [ggplot2 - bar plot with both stack and dodge](https://stackoverflow.com/questions/12715635/ggplot2-bar-plot-with-both-stack-and-dodge) – DavideBrex May 28 '20 at 16:47
  • I am looking for a chart that does not share certain variables. – Leila Al May 28 '20 at 17:24

1 Answers1

1

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