Search code examples
rggplot2facetfacet-wrap

How to extract single plots from facet_plot and maintain scaling?


From one dataframe of data in long format, the first plot call below gives me this matrix of joyplots: enter image description here There is one ridgeline and color scale across each of the 13 scenarios.

However, when I try to show just one plot per page, in the looped 'SingleScenario' plot call below, the scaling is done for the individual subset of data per scenario min and max (each plot has the full yellow to purple color scale, and I'm not sure if the ridgeheight scale is preserved or reset).

How do I plot individual scenarios as single pages and keep the original scaling? This way, differences will be visualized by paging down through a 13-page pdf.

Here is my code:

library(ggplot2)
library(viridis)

matrix <- ggplot(df, aes(watermonth, as.integer(wateryear), height = inflow, group=as.integer(wateryear)
           , fill=cumWYinf))  + geom_ridgeline(stat = "identity",
          show.legend = F, scale = 0.005, alpha = 0.8) + facet_wrap(~scenario, nr=4, nc=4) +
          scale_fill_viridis() 


scenarios <- c("q0", "e1", "e2", "e3", "e4", "e5", "cwc30", "l1", "l2", "l3", "l4", "l5", "cwc70")

for(i in 1:length(scenarios)) {

facets <- c(paste0(scenarios[i]))

SingleScenario <- ggplot(df[df$scenario %in% facets,], aes(watermonth, as.integer(wateryear),
      height = inflow, group=as.integer(wateryear), fill = cumWYinf)) +
      geom_ridgeline(stat = "identity", show.legend = F, scale = 0.005, alpha = 0.9) +
      + facet_wrap(~scenario, nr=1, nc=1) + scale_fill_viridis() 

SingleScenario
ggsave(paste(scenarios[i],".pdf"), dpi = 300, width = 17, height = 11, units = "in") }

Thank you.

 date        watermonth wateryear inflow scenario SacWYT SJRWYT cumWYinf
  <date>           <dbl>     <dbl>  <dbl>    <chr>  <int>  <int>    <dbl>
1 1921-10-31          1      1922  66.38       q0      2      2  2293.78
2 1921-11-30          2      1922  50.65       q0      2      2  2293.78
3 1921-12-31          3      1922  82.09       q0      2      2  2293.78

Solution

  • It's very hard to answer without having example dataset to test my prediction, but can you try adjusting fill with limits = ...:

    scale_fill_viridis(limits = range(df$cumWYinf))

    This way all plots will have the same scale.