I would like to create a stacked barplot with three different legends for different groupings of data.
For example, given the following dataframe:
Year <- as.factor(c(rep(1, 10), rep(2, 10), rep(3,10), rep(4,10), rep(5,10), rep(6,10)))
Category <- as.factor(c(rep("a", 15), rep("b", 10), rep("c", 10), rep("d",10), rep("e", 10), rep("f", 5)))
Region <- as.factor(c(rep("region1", 25), rep("region2", 20), rep("region3",15)))
data <- data.frame(Year, Category, Region)
I would like to plot a stacked barplot of the count of each Category by year.
ggplot() + geom_bar(data=data,aes(x=Year, fill=Category))
However, instead of having one legend for Category (like above) I would like to have three legends with Category subset by Region (ie the legend titled "region1" would show Categories "a" and "b"; the legend titled "region2" would show Categories "c" and "d"; and the legend titled "region3" would show Categories "e" and "f".
I have tried referring to these two threads: Legends for multiple fills in ggplot and R: Custom Legend for Multiple Layer ggplot. However, I have had no luck applying them to a barplot. Any help would be greatly appreciated!