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.
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:
rsltProf = rslt %>%
filter(group == "Professionals" & avg > 0) %>%
group_by(gender) %>%
arrange(avg, .by_group = TRUE)
str(rsltProf$genXrce)
And I get the following output:
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
Great, this is exactly what I want. However when I graph it with ggplot, it produces the following result:
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.
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.
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:
ggplot(data = rsltProf, mapping = aes(x =fct_reorder(!!as.name(genXrce), avg), y = avg, fill = genXrce))
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....
The above ggplot produces the below graph, which jumbles the genders: