2

I have a data set where I need to represent a stacked bar chart for two cohorts over three time periods. Currently, I am faceting by year, and filling based on probability values for my DV (# of times,t, that someone goes to a nursing home; pr that t=0, t=1, ... t >= 5). I am trying to figure out if it is possible to introduce another color scale, so that each of the "Comparison" bars would be filled with a yellow gradient, and the treatmetn bars would be filled with a blue gradient. I figure the best way to do this may to be to overlay the two plots, but I'm not sure if it is possible to do this in ggplot (or some other package.) Code and screenshot are below:

         tempPlot <- ggplot(tempDF,aes(x = HBPCI, y = margin,  fill=factor(prob))) + 
      scale_x_continuous(breaks=c(0,1), labels=c("Comparison", "Treatment"))+
      scale_y_continuous(labels = percent_format())+
      ylab("Prob snf= x")+
      xlab("Program Year")+
      ggtitle(tempFlag)+
      geom_bar(stat="identity")+
      scale_fill_brewer(palette = "Blues")+ #can change the color scheme here.
      theme(axis.title.y =element_text(vjust=1.5, size=11))+
      theme(axis.title.x =element_text(vjust=0.1, size=11))+
      theme(axis.text.x = element_text(size=10,angle=-45,hjust=.5,vjust=.5))+
      theme(axis.text.y = element_text(size=10,angle=0,hjust=1,vjust=0))+
      facet_grid(~yearQual, scales="fixed")

enter image description here

1 Answers1

4

You may want to consider using interaction() -- here's a reproducible solution:

year <- c("BP", "PY1", "PY2")
type <- c("comparison", "treatment")

df <- data.frame(year = sample(year, 100, T),
                 type = sample(type, 100, T),
                 marg = abs(rnorm(100)),
                 fact = sample(1:5, 100, T))
head(df)
#   year       type      marg fact
# 1   BP comparison 0.2794279    3
# 2  PY2 comparison 1.6776371    1
# 3   BP comparison 0.8301721    2
# 4  PY1  treatment 0.6900511    1
# 5  PY2 comparison 0.6857421    3
# 6  PY1  treatment 1.4835672    3

library(ggplot2)

blues <- RColorBrewer::brewer.pal(5, "Blues")
oranges <- RColorBrewer::brewer.pal(5, "Oranges")

ggplot(df, aes(x = type, y = marg, fill = interaction(factor(fact), type))) +
  geom_bar(stat = "identity") +
  facet_wrap(~ year) +
  scale_fill_manual(values = c(blues, oranges))

Plot

JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116