egar
egar

Reputation: 23

Side by side stacked barplots with different colors

I am trying to create a figure with two stacked barplots side by side where each features a different color scheme. Here is some model code:

prob.out = function(lam){
  out1 = dpois(x = 0:3, lambda = lam)
return(c(1-sum(out1), sort(out1)))
}
Prob.out = Vectorize(prob.out, SIMPLIFY = "vector")

synth.data = data.frame(
  year = rep(2019:2021, each = 10) %>% as.character(), 
  small.cat = rep(rep(c("a", "b"), each = 5), times = 3), 
  response.var = round(c(Prob.out(lam = c(1, .7, .9, .6, .8, .5)))*10000,0)
)
library(ggplot2)

ggplot(data = synth.data, aes(small.cat, y = response.var, color = response.var, fill = response.var)) +
  geom_col(position = "fill") + 
  facet_wrap(~year)

Is there a way to change the small.cat color scales independently of each other?

I am aiming to get a figure that looks like this:

enter image description here

Upvotes: 2

Views: 178

Answers (1)

stefan
stefan

Reputation: 125607

One option to achieve your desired result would be the ggnewscale package which allows for multiple scales for the same aesthetic. To make this work you have to add the bars for each small.cat via a separate geom_col:

library(ggplot2)
library(ggnewscale)

ggplot(data = synth.data, aes(small.cat, y = response.var)) +
  geom_col(data = subset(synth.data, small.cat == "a"), aes(color = response.var, fill = response.var), position = "fill") + 
  new_scale_fill() +
  new_scale_color() +
  geom_col(data = subset(synth.data, small.cat == "b"), aes(color = response.var, fill = response.var), position = "fill") + 
  scale_fill_gradient(low = "red", high = "darkred") +
  scale_color_gradient(low = "red", high = "darkred") +
  facet_wrap(~year)

Upvotes: 1

Related Questions