[英]Reordering a percent stacked bar chart by gender and values
I'm trying to reorder my values by gender, from highest women to lowest women.我试图按性别重新排列我的价值观,从最高的女性到最低的女性。
First values of this dataset are:该数据集的第一个值是:
sex,values,citizen_full
F,543,Aghanistan
M,376,Afghanistan
F,131,Albania
M,141,Albania
F,134,Argentina
M,107,Argentina
F,325,Austria
M,231,Austria
ggplot(dataframe, aes(x = factor(citizen_full), y = values, fill = sex)) +
geom_bar(position = 'fill', stat = 'identity') +
theme_minimal()
You can use the fct_reorder
function:您可以使用
fct_reorder
function:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.