gpt4 book ai didi

r - R 中性别过剩的人口金字塔

转载 作者:行者123 更新时间:2023-12-02 18:32:08 26 4
gpt4 key购买 nike

在维基百科上,有一个奇妙的人口金字塔,显示了性别过剩。我如何使用 ggplot2 和/或 plotly 在 R 中重新创建它?

它本质上是一个双层堆叠的条形图,已定向 90 度。

# Here is some population data

library(wpp2019)
# Male
data(popM)
# Female
data(popF)

Population Pyramid with Gender surplus

Wikipedia: Demographics of the United States

最佳答案

在下面的代码中,大部分工作都在数据整形中,而 ggplot 代码相对简单。

library(wpp2019)
library(tidyverse)
data(popM)
data(popF)

list(Male=popM, Female=popF) %>%
imap(~.x %>%
filter(name=="World") %>%
select(age, !!.y:=`2020`)) %>%
reduce(full_join) %>%
mutate(age = factor(age, levels=unique(age)),
`Female surplus` = pmax(Female - Male, 0),
`Male surplus` = pmax(Male - Female, 0),
Male = Male - `Male surplus`,
Female = Female - `Female surplus`) %>%
pivot_longer(-age) %>%
mutate(value = case_when(grepl("Male", name) ~ -value,
TRUE ~ value),
name = factor(name, levels=c("Female surplus", "Female",
"Male surplus", "Male"))) %>%
ggplot(aes(value, age, fill=name)) +
geom_col() +
geom_vline(xintercept=0, colour="white") +
scale_x_continuous(label=function(x) ifelse(x < 0, -x, x),
breaks=scales::pretty_breaks(6)) +
labs(x=NULL, y=NULL, fill=NULL) +
scale_fill_discrete(type=RColorBrewer::brewer.pal(name="RdBu", n=4)[c(1,2,4,3)],
breaks=c("Male surplus", "Male", "Female","Female surplus")) +
theme_bw() +
theme(legend.position="bottom")

作为另一种选择,您可以将垂直轴标签放置在条形之间。这个版本也使用分面,所以我们可以很容易地按性别标记分面。然后在图例中,我们只需要标记条形的多余部分。

library(ggpol)
library(ggthemes)

list(Male=popM, Female=popF) %>%
imap(~.x %>%
filter(name=="World") %>%
select(age, !!.y:=`2020`)) %>%
reduce(full_join) %>%
mutate(age = factor(age, levels=unique(age)),
`Female surplus` = pmax(Female - Male, 0),
`Male surplus` = pmax(Male - Female, 0),
Male = Male - `Male surplus`,
Female = Female - `Female surplus`) %>%
pivot_longer(-age) %>%
mutate(facet = factor(ifelse(grepl("Female", name), "Female", "Male"),
c("Male","Female")),
value = case_when(grepl("Male", name) ~ -value,
TRUE ~ value),
name = factor(name, levels=c("Female surplus", "Female",
"Male surplus", "Male"))) %>%
ggplot(aes(value, age, fill=name)) +
geom_col() +
geom_vline(xintercept=0, colour="white") +
scale_x_continuous(label=function(x) ifelse(x < 0, -x, x),
breaks=scales::pretty_breaks(3),
expand=c(0,0)) +
labs(x=NULL, y=NULL, fill=NULL) +
facet_share(vars(facet), scales="free_x") +
scale_fill_discrete(type=RColorBrewer::brewer.pal(name="RdBu", n=4)[c(1,2,4,3)],
breaks=c("Male surplus", "Female surplus")) +
theme_clean() +
theme(legend.position="bottom",
legend.background=element_blank(),
legend.key.height=unit(4,"mm"),
legend.margin=margin(t=0),
plot.background=element_blank(),
strip.text=element_text(face="bold", size=rel(0.9)))

关于r - R 中性别过剩的人口金字塔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69287518/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com