title: R - ggplot2 - limit bar chart output for categorical data
body: <p>I am trying to create a bar chart in ggplot2 that limits output on the x-axis to the top-10% most frequent categorical variables.</p>
  
  <p>My dataframe is a dataset that contains statistics on personal loans. I am examining the relationship between two categories, Loan Status and Occupation. </p>
  
  <p>First, I want to limit Loan Status to loans that have been "charged off." Next, I want to plot how many loans have been charged off across various occupations using a bar chart. There are 67 unique values for Occupation - I want to limit the plot to only the most frequent occupations (by integer or percentage, i.e. "7" or "10%" works).</p>
  
  <p>In the code below, I am using the forcats function <code>fct_infreq</code> to order the bar chart by frequency in descending order. However, I cannot find a function to limit the number of x-axis categories. I have experimented with <code>quantile</code>, <code>scale_x_discrete</code>, etc. but those don't seem to work for categorical data.</p>
  
  <p>Thanks for your help!</p>
  
  <pre><code>df %&gt;% filter(LoanStatus %in% c("Chargedoff")) %&gt;% 
  ggplot() +
    geom_bar(aes(fct_infreq(Occupation)), stat = 'count') +
    scale_x_discrete(limits = c(quantile(df$Occupation, 0.9), quantile(df$Occupation, 1)))
  </code></pre>
  
  <p>Resulting error:</p>
  
  <blockquote>
    <p>Error in (1 - h) * qs[i] : non-numeric argument to binary operator</p>
  </blockquote>
  
  <p><strong>UPDATE:</strong>
  Using Yifu's answer below, I was able to get the desired output like this:</p>
  
  <pre><code>pd_occupation &lt;- pd %&gt;% 
    dplyr::filter(LoanStatus == "Chargedoff") %&gt;%
    group_by(Occupation) %&gt;% 
    mutate(group_num = n())
  
  table(pd_occupation$group_num)#to view the distribution
  
  ggplot(subset(pd_occupation, group_num &gt;= 361)) +
    geom_bar(aes(fct_infreq(Occupation)), stat = 'count') +
    ggtitle('Loan Charge-Offs by Occupation')
  </code></pre>