title: reordering factors in a grouped variable so it can be graphed in order with ggplot2
body: <p>I am attempting to make a graph that shows an average age by gender-race groups. The graph itself should show this information in order of lowest average age to highest average age, grouped by overall gender. </p>
  
  <p>I'm working out of a dataset that is grouped by work class, gender/race, gender, and average age. I have been able to successfully order this by gender with the following code:</p>
  
  <pre><code>rsltProf = rslt %&gt;% 
        filter(group == "Professionals" &amp; avg &gt; 0) %&gt;%
        group_by(gender) %&gt;%
        arrange(avg, .by_group = TRUE)
  str(rsltProf$genXrce)
  </code></pre>
  
  <p>And I get the following output:</p>
  
  <pre><code>    group          genXrce   gender      avg
  1 Professionals Female-Asian Female 33.25397
  2 Professionals Female-Other Female 37.55000
  3 Professionals Female-White Female 39.89632
  4 Professionals Female-Black Female 39.94118
  5 Professionals   Male-Other   Male 32.80000
  6 Professionals   Male-Asian   Male 37.86667
  7 Professionals   Male-Black   Male 38.69767
  8 Professionals   Male-White   Male 38.85294
  Factor w/ 9 levels "Female-Asian",..: 4 2 3 1 9 7 8 6
  </code></pre>
  
  <p>Great, this is exactly what I want. However when I graph it with ggplot, it produces the following result:</p>
  
  <p><a href="https://i.stack.imgur.com/r5Yua.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r5Yua.png" alt="output"></a></p>
  
  <p>clearly, this is because ggplot2 is graphing by the order of the factors rather than the order of the arranged dataframe. I have tried multiple ways to relevel the genXrce based on how it's arranged in the above code to no avail, including relevel, mutate, and reorder.</p>
  
  <p>My question is: How can I reorder/arrange the data in such a way that ggplot2 will produce a graph that gives ascending averages grouped by gender, in the same way as the table I produced does? Any advice much appreciated.</p>
  
  <p>EDIT 1:
  In a below comment it was suggested to do use forcats or a similar function to arrange the graph through ggplot. An example like so:</p>
  
  <pre><code>ggplot(data = rsltProf, mapping = aes(x =fct_reorder(!!as.name(genXrce), avg), y =  avg, fill = genXrce))
  </code></pre>
  
  <p>However, this will arrange ALL the genXrce factors by average, and it will no longer be separate by gender. to be clear, the barplot order should be the same as the table --> Female-White, Female-Black, Female-Other, Female-Asian, Male-White, Male-Black....</p>
  
  <p>The above ggplot produces the below graph, which jumbles the genders:
  <a href="https://i.stack.imgur.com/y44y1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y44y1.png" alt="2nd graph"></a></p>