library(tidyverse)
crackers.df <- read_csv("./data/chap5/crackers-loc.csv")
by.locprom <- crackers.df %>%
  group_by(promotion,location) %>%
  summarise(mx.pre=mean(x.pre)) %>%
  mutate(lab.ypos=rev(cumsum(rev(mx.pre)))) %>%
  ungroup()
sp <- ggplot(data=by.locprom,
             mapping=aes(x=promotion,y=mx.pre,fill=location))
#-- Create stacked bar plot
stacked <- sp +
  geom_bar(stat="identity",width = 0.5) +
  scale_fill_manual(values=c("red","forestgreen","yellow")) +
  labs(y="Average number pre-promotion sales\n") +
  theme_light()
# Adding labels to the sub-bars 
stacked +
  geom_text(aes(y=lab.ypos,label=round(mx.pre,2)),
            fontface="bold",color="black",vjust=4)
ggsave(filename="./images/chap5/bar@vstackedbar.pdf", 
       width = 4.5,height = 3.8,units = "in")
# create horizontal stacked bar chart with labels
stacked + 
  coord_flip() +
  geom_text(aes(y=lab.ypos,label=format(round(mx.pre,1),nsmall=1)),
            fontface="bold",color="black",hjust=2)
ggsave(filename="./images/chap5/bar@hstackedbar.pdf", width = 4.5,
       height = 3.8,units = "in")