Background color rectangles in ggplot according to a factor value

Viewed 3054

I am looking for a way to display color rectangles in a ggplot2 background according to a factor level. Here is a dput of the data :

    structure(list(date = structure(c(6L, 8L, 3L, 4L, 5L, 7L, 1L, 
2L), .Label = c("01/05/2012", "10/05/2012", "17/05/2011", "18/05/2011", 
"19/05/2011", "20/12/2013", "24/04/2012", "26/12/2013"), class = "factor"), 
    Polyols = c(122, 5.25, 48.21, 41.59, 84.97, 64.75, 153.97, 
    49.14), Year = c(2013L, 2013L, 2011L, 2011L, 2011L, 2012L, 
    2012L, 2012L), Season = structure(c(2L, 2L, 1L, 1L, 1L, 1L, 
    1L, 1L), .Label = c("Spring", "Winter"), class = "factor"), 
    Site = structure(c(3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L), .Label = c("GAP", 
    "OPE-ANDRA", "Peyrusse Vieille"), class = "factor"), Typology = structure(c(1L, 
    1L, 2L, 2L, 2L, 1L, 1L, 1L), .Label = c("Rural", "Urban"), class = "factor")), .Names = c("date", 
"Polyols", "Year", "Season", "Site", "Typology"), class = "data.frame", row.names = c(NA, 
-8L))

What I'd like to get is a color rectangle behind each "typology" as shown in the picture below

enter image description here

I found This topic but couldn't find a way to adjust it to my case.

I tried

g <- ggplot(data) + 
     geom_bar(aes(x= Site, y= Polyols, fill= Season, colour= Season),
              show.legend = TRUE,stat="identity",position= position_dodge()) +
    theme(axis.text.x = element_text(angle=90, hjust=1, vjust=0))

g <- g + geom_rect(data=data, (aes(xmin=Typology, xmax=Typology, 
                   ymin=0,ymax=200,fill=factor(Typology))))
g

Could someone help ?

1 Answers

Here is an attempt:

ggplot(dat)+
  geom_rect(fill = hue_pal()(4)[as.numeric(dat$Typology)],xmin = -Inf,xmax = Inf,
            ymin = -Inf,ymax = Inf, alpha = 0.1, color = "black") +
  geom_col(aes(x = Site, y = Polyols, fill = Season))+
  coord_cartesian(ylim = c(-50, max(aggregate(Polyols ~ Site, sum, data = dat)[,2])))+
  facet_grid(~Typology, scales = "free_x", space="free_x", switch = "x") +
  geom_text(aes(x = Site, y = -1, label = Site), angle = 90, hjust = 1) +
  theme(axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        panel.spacing = unit(0, "lines"))+
  xlab("")

enter image description here

Facet the plot according to the background fill, use geom_rect to fill the background. Remove x axis ticks and labels, use geom_text to annotate the x axis. Remove spacing from facets.

Related