title: Set and unset default ggplot colors within function
body: <p>I am working on a custom theme function. As part of this function, there will be several palette choices that can be applied to different scales. However, I wish to set a default palette if none is specified. I would only like to set this palette when the function is called and, if the function is not called, use ggplot's default. I tried setting it within the fill arguments, but if a non-discrete scale is supplied, ggplot gives an error. Likewise, if I set a gradient palette in the arguments, errors also appear.</p>
  <p>In the below function, I use <code>options(ggplot2.discrete.fill = rep(pal,3))</code> to set the palette in the beginning of the function. I use <code>options(ggplot2.discrete.fill = scale_fill_hue)</code> at the end to reset to the default ggplot palette, however, this is not respected.</p>
  <pre><code>pal = c(&quot;#F37321&quot;, &quot;#8DC63F&quot;, &quot;#13B5EA&quot;, &quot;#9B5BA5&quot;, &quot;#009F93&quot;, &quot;#77787B&quot;)
  
  
  mytheme &lt;- function(fill = NULL, name = waiver(),
                      sequential = NULL){
    
    # set default if no palette is specified
    options(ggplot2.discrete.fill = rep(pal,3))
    
    # set custom fill arguments
    # fill ----
    scale_fill_custom &lt;- function(fill, name=name, ...) {
      scale_fill_manual(values=fill, name, ...)}
    
    # gradient fill
    scale_fill_gradientn_custom &lt;- function(sequential, name=name, ...){
      scale_fill_gradientn(colors=sequential, name=name, ...)
    }
    
    # theme ----
    themer &lt;- function() {
      amp &lt;- theme_minimal()
    }
    
    # output of function ----
    theme_object &lt;- list(
      if(is.null(fill)) { NULL } else { scale_fill_custom(fill, name, na_color) },
      if(is.null(sequential)) { NULL } else {
        scale_fill_gradientn_custom(sequential, name) },
      themer())
    
    
    return(theme_object)
  
    # return to ggplot default
    options(ggplot2.discrete.fill = scale_fill_hue)
    
    
  }
  </code></pre>
  <p>The following shows the correct colors:</p>
  <pre><code>
  mtcars %&gt;%
    slice(1:10) %&gt;%
    rownames_to_column(&quot;mfg&quot;) %&gt;%
    ggplot(aes(x=mpg, y=reorder(mfg, mpg), fill=as.factor(mpg)))+
    geom_col()+
    mytheme()
  </code></pre>
  <p>I would expect the following to show the default ggplot colors</p>
  <pre><code>
  mtcars %&gt;%
    slice(1:10) %&gt;%
    rownames_to_column(&quot;mfg&quot;) %&gt;%
    ggplot(aes(x=mpg, y=reorder(mfg, mpg), fill=as.factor(mpg)))+
    geom_col()
    # note - no mytheme() call
  </code></pre>
  <p>Any idea how to implement this correctly?</p>