title: Is it possible to save a ggplot in RDS format with a global variable in the ggplot() call?
body: <p>RDS files are wonderful for sharing R objects between R files. And I often share ggplot objects between R files when I have a particularly complicated layout. Usually this works great.</p>
  
  <p>My grumble is that if your ggplot() function call contains a global variable, that variable is lost when you save the plot as an .rds file. So when you load the plot in a new R file, it's no bueno. Information is lost.</p>
  
  <p>Does anyone know a clever solution for this problem? The work-arounds I have come up with are clunky. And I really don't want to regress to the default save() and load() functions.</p>
  
  <p>How about a few examples. I'll start with a chunk that works. Then I'll show how things fall apart with a global variable.</p>
  
  <p><strong>NOTE: This code will put a couple junk files in your current working directory. Ye be warned.</strong></p>
  
  <pre><code># Preliminaries -------------------------------------------
  library(tibble)
  library(magrittr)
  library(ggplot2)
  
  # Fake data
  x &lt;- 1:5 %&gt;% as.factor()
  y &lt;- rnorm(5)
  df &lt;- data_frame(x, y)
  
  
  # First an example that works -----------------------------
  # Notice how the color palette is 
  # defined within scale_fill_manual()
  this_plot_works &lt;- ggplot(df, aes(x, y, fill = x)) + 
    geom_bar(stat = "identity") + 
    scale_fill_manual(values = c("red", "blue", "orange", "green", "purple"))
  
  # Save plot to file
  saveRDS(this_plot_works, file = "this_plot_works.rds")
  
  # To simulate the behavior of moving to a new R file
  # let's remove the ggplot object from the environment.
  rm(this_plot_works)
  
  # Now, pretending we're in a new R file, load the plot
  this_plot_works_reloaded &lt;- readRDS("this_plot_works.rds")
  this_plot_works_reloaded
  </code></pre>
  
  <p>Now I'll specify the color palette as a global variable, and I'll call it within the ggplot function (I guess, technically, it's called in the 'scale_fill_manual()' function, but you know what I mean). This strategy will not work.</p>
  
  <pre><code># Second example that won't work --------------------------
  # Specify color palette as a global variable
  col_pal &lt;- c("red", "blue", "orange", "green", "purple")
  
  # Plot
  # Note that the color palette is tied to the global variable
  this_plot_wont_work &lt;- ggplot(df, aes(x, y, fill = x)) + 
    geom_bar(stat = "identity") + 
    scale_fill_manual(values = col_pal) 
  
  # Save the plot to file
  saveRDS(this_plot_wont_work, file = "this_plot_wont_work.rds")
  
  # Again, let's remove the key global variables
  # and pretend we're switching to a new R file
  rm(this_plot_wont_work, col_pal)
  
  # Load the plot
  this_plot_wont_work_reloaded &lt;- readRDS("this_plot_wont_work.rds")
  this_plot_wont_work_reloaded
  </code></pre>