Search code examples
rggplot2dplyrlapply

Retain levels when generating multiple plots from dplyr filtered data


Looking to retain levels when generating multiple plots via lapply and filtered data:

library(purrr)
library(tidyverse)

test <- data.frame(`1` = rpois(10,3),`2`=rpois(10,3), `3` = rpois(10,3))

ccf.func <- function(i,j){
  dat <- ccf(test[i],test[j],plot=FALSE,type="correlation")
  ccf.dat <- data.frame(ccf=dat$acf,lag=dat$lag,first=i,second=j)
  return(ccf.dat)
}

dat <- map_dfr(1:3, function(i) map_dfr(1:3, function(j) ccf.func(i,j)))

lapply(0:2, function(i)
  ggplot(dat |> filter(lag == i)) +
           geom_tile(aes(x=first,y=second,fill=ccf)))

enter image description here enter image description here enter image description here

These all have differing fill scale levels, how do I unify them?


Solution

  • You can use scale_fill_continuous to set the same limits for every plots:

    lapply(0:2, function(i)
      ggplot(dat |> filter(lag == i)) +
        geom_tile(aes(x=first,y=second,fill=ccf)) +
        scale_fill_continuous(limits = c(-1, 1)))