title: How can I replace a factor levels with the top n levels (by some metric), plus [other]?
body: <p>For a factor with more than a sensible number of levels to color in a graph, I want to replace any levels that are not in the 'top 10' with 'other'.</p>
  
  <p><em>Alternate Question:</em> How do I reduce my factor levels to the number rcolorbrewer can plot as separate colors? </p>
  
  <p>For example, if I want to plot number of homeruns per decade from the baseball data:</p>
  
  <pre><code>require(ggplot2)
  qplot(data=baseball,10*year%/%10,hr,
    stat="identity",geom="bar")
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/GK3Nz.png" alt="simple graph to set the scene"></p>
  
  <p>Perhaps I'd like to see what teams contributed to this:</p>
  
  <pre><code>qplot(data=baseball,10*year%/%10,hr,
    fill=team,
    stat="identity",geom="bar")
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/hGZHo.png" alt="too many teams to tell colors apart or plot on page"></p>
  
  <p>This creates too many color levels!  The colors are so similar you can't distinguish them, and there are so many they won't fit on the screen.</p>
  
  <p>I'd really like to see the top X (7) teams (by total homerun count) and then the rest all lumped together in a single category/color called 'other'.</p>
  
  <p>Let's imagine we have a function called <code>hotfactor</code> which knows how to do this:</p>
  
  <pre><code>hotfactor(afactor,orderby,count)={ ??? }
  
  qplot(data=baseball,10*year%/%10,hr,
    fill=hotfactor(factor(team),hr,n=7),
    stat="identity",geom="bar") + 
    scale_fill_brewer("team","Dark2")
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/fb650.png" alt="sample image for solution"></p>
  
  <p>So what can I use for 'hotfactor'?</p>