I am using ggplot2 in R and am trying to create a stacked bar plot on the y-axis to show a continuous numeric variable (var1: 1, 2, 3...) with fill categories on a categorical variable (var2: A, B, C) over a continuous numeric x-axis variable (var3: 1, 2, 3...). However I would also like to separate by another categorical variable (var4: L1, L2, L3) per each x-axis variable.
For example I am easily able to create either of these via position 'stack' (Stack) or 'dodge' (Dodge) respectively (see below) but I would like them combined. Ideally the colours on the stacks are consistent and the dodge is outlined or I would even just label them manually if necessary.
library(ggplot2)
#Data
set.seed(3)
data = data.frame(var1 = 1:15,
var2 = sample(c("A","B","C"),15, replace=TRUE),
var3 = sample(c("1","2","3","4","5"), 15, replace=TRUE),
var4 = sample(c("L1","L2","L3"), 15, replace=TRUE))
#Stack
ggplot(data, aes(x=as.numeric(var3), y=var1, fill=var2))+
geom_bar(aes(), stat="identity", position="stack")+
theme(legend.position="right")+
labs(title="Stack")+
theme_bw()
#Dodge
ggplot(data, aes(x=as.numeric(var3), y=var1, fill=var4))+
geom_bar(aes(), stat="identity", position="dodge")+
theme(legend.position="right")+
labs(title="Dodge")+
theme_bw()
#Facet
ggplot(data, aes(x=as.numeric(var3), y=var1, fill=var2))+
geom_bar(aes(), stat="identity", position="stack")+
theme(legend.position="right")+
labs(title="Facet")+
theme_bw()+
facet_wrap(~var4)
I am aware of faceting (Facet) and know it to be a common solution and have done that as well. However I would really like to do both at the same time such that there is a single plot (y vs x) with stacked and adjacent bar plots. It seems pointless here but I have a much larger dataset such that there are values and combinations of var2, var3, and var4. If this is impossible I will rely on faceting but it seems like something that should be possible.