Search code examples
rggplot2data-visualizationbackground-colorfacet-wrap

Color facets in ggplot by continuous variable


** Edited with Repeatable Data **

I have a data.frame with plots of growth over time for 50 experimental treatments. I have plotted them as a faceted 5x10 plot grid. I also ordered them in a way that makes sense considering my experimental treatments.

I ran a regression function to find growth rate in each treatment, and saved the slope values in another data frame. I have plotted the data, the regression line, and the value of growth rate, but I want to color the backgrounds of the individual faceted plots according to that regression slope value, but I can't figure out how to set color to call to a continuous variable, and especially one from a different df with a different number of rows (original df has 300 rows, df I want to call has 50 - one for each treatment).

My code is as follows:

Df:

df <- data.frame(matrix(ncol = 3,nrow=300))
colnames(df) <- c("Trt", "Day", "Size")
df$Trt <- rep(1:50, each=6)
df$Day <- rep_len(1:6, length.out=300)
df$Size <- rep_len(c(3,5,8,9,12,12,3,7,10,16,17,20),length.out = 300)

Regression function and output dataframe:

regression=function(df){
  reg_fun<-lm(formula=df$Size~df$Day) 
  slope<-round(coef(reg_fun)[2],3) 
  intercept<-round(coef(reg_fun)[1],3) 
  R2<-round(as.numeric(summary(reg_fun)[8]),3)
  R2.Adj<-round(as.numeric(summary(reg_fun)[9]),3)
  c(slope,intercept,R2,R2.Adj)
}
library(plyr)
slopevalues<-ddply(df,"Trt",regression)
colnames(slopevalues)<-c ("Trt","slope","intercept","R2","R2.Adj")

Plot:

ggplot(data=df, aes(x=Day, y=Size))+
geom_line() +
geom_point() +
xlab("Day") + ylab("Size (μm)")+
geom_smooth(method="lm",size=.5,se=FALSE)+ 
geom_text(data=slopevalues,
            inherit.aes=FALSE, 
            aes(x =1, y = 16,hjust=0,
            label=paste(slope)))+ 
facet_wrap(~ Trt, nrow=5)

What I want to do is color the backgrounds of the individual graphs according to the slope value (slopevalues$slope) on a gradient. My real data are not just 2 values repeated, so I want to do this on a gradient of colors according to that value.

Any advice welcome.

enter image description here


Solution

  • You can use geom_rect with infinite coordinates to do this:

    ggplot(data=df, aes(x=Day, y=Size))+
      ## This is the only new bit
      geom_rect(
        aes(fill = slope, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf), 
        slopevalues,
        inherit.aes = FALSE
      ) +
      ## New bit ends here
      geom_line() +
      geom_point() +
      xlab("Day") + ylab("Size (μm)")+
      geom_smooth(method="lm",size=.5,se=FALSE)+ 
      geom_text(data=slopevalues,
                inherit.aes=FALSE, 
                aes(x =1, y = 16,hjust=0,
                    label=paste(slope)))+ 
      facet_wrap(~ Trt, nrow=5)
    

    enter image description here