Order of individual segments within stacked bar plot

Hi - I'm pretty sure I need to reorder the factor that's filling the bars before I pipe into ggplot, but I can't get it to work. Without having to manually reorder the factor levels, how can I have the bar segments be ordered in a consistent way? i.e. the highest value of marital being the bottom bar for each grouping of race. Thank you!

forcats::gss_cat %>% 
  count(race,marital) %>% 
  mutate(marital=fct_reorder(marital,n)) %>% 
  geom_col(position = 'fill')

I think you need forcats::fct_infreq().


gss_cat %>% 
  count(race, marital) %>% 
  mutate(marital = fct_infreq(marital)) %>%
  ggplot(aes(race, n, fill = marital)) +
  geom_col(position = 'fill')

Created on 2020-04-17 by the reprex package (v0.3.0)

Thanks for the reply - do you see though how for Black, Never married is the bar w/ the highest proportion? I'm trying to get that bar to be at the bottom. I think the issue is that the order of levels varies across groups and I can't figure out how to tell ggplot to sort them a specific way within each group.

I suspected that was what you were after. However, as far as I know, this is not trivial since the ordering of factor levels applies to the entire variable; it is not defined at the group level.

Sorry I can't offer more help. If someone else can show a way out I'd be very interested.

No worries, thanks for taking a look at this

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.