title: ggplot: How to create a discrete color palette that fits the data automatically?
body: <p>I have a customized function that I use for all my plots instead of the plain <code>ggplot</code>:</p>
  
  <pre><code>my_ggplot &lt;- function(...){
      ggplot(...) +
      theme_bw() +
      scale_colour_manual(values=get_palette(20)) +
      theme(axis.text.x=element_text(size=15),
            axis.text.y=element_text(size=15),
            axis.title.y=element_text(vjust=-.5, size=15, face="bold"),
            axis.title.x=element_text(vjust=-.5, size=15, face="bold"),
            plot.title=element_text(vjust=1, size=18, face="bold"),
            legend.title=element_text(size=15, face="bold"),
            plot.margin=unit(c(2,1,2,2), "lines")) # T R B L
  }
  </code></pre>
  
  <p>Now I can do something like:</p>
  
  <pre><code>my_ggplot(molten_df, aes(timepoint,count,group=gene_symbol)) +
      geom_line(aes(color=gene_symbol), lwd=1.5)
  </code></pre>
  
  <p>This gives me decent label font sizes and my own color scale. Unfortunately I have to manually encode the palette size (20) to my get_palette function, which returns a different palette depending on the number I pass it.</p>
  
  <p>My question: is there a way to infer the number of levels that the color aesthetic will have so my_ggplot doesn't crash when I need to plot 21 colors? I guess this is the way ggplot does it, but I can't seem to find the relevant function in their source code.</p>
  
  <p><strong>Answered by @user946850</strong>
  This is what I ended up doing:</p>
  
  <pre><code>my_ggplot &lt;- function(...){
      ggplot(...) +
      theme_bw() +
      discrete_scale("colour", "my_scale", dyn_palette()) +
      theme(axis.text.x=element_text(size=15),
            axis.text.y=element_text(size=15),
            axis.title.y=element_text(vjust=-.5, size=15, face="bold"),
            axis.title.x=element_text(vjust=-.5, size=15, face="bold"),
            plot.title=element_text(vjust=1, size=18, face="bold"),
            legend.title=element_text(size=15, face="bold"),
            plot.margin=unit(c(2,1,2,2), "lines")) # T R B L
  }
  
  dyn_palette &lt;- function(){
    function(n){
      get_palette(n)
    }
  }
  </code></pre>