Вы можете использовать функцию fct_reorder
:
df <- tibble::tribble(
~sex, ~values, ~citizen_full,
"F", 543L, "Aghanistan",
"M", 376L, "Afghanistan",
"F", 131L, "Albania",
"M", 141L, "Albania",
"F", 134L, "Argentina",
"M", 107L, "Argentina",
"F", 325L, "Austria",
"M", 231L, "Austria"
)
library(dplyr)
library(ggplot2)
library(forcats)
df %>%
group_by(citizen_full, sex) %>%
mutate(sum_sex_grouped = sum(values)) %>%
group_by(citizen_full) %>%
mutate(sum_citizien = sum(values),
sex_percent = sum_sex_grouped/sum_citizien,
percent_women = if_else(sex == "F", sex_percent, 0)) %>%
ggplot(aes(x = fct_reorder(citizen_full, desc(percent_women)), y = values, fill = sex)) +
geom_bar(position = 'fill', stat = 'identity') +
theme_minimal()