欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > 【R语言可视化】人口金字塔

【R语言可视化】人口金字塔

2025/4/2 9:42:12 来源:https://blog.csdn.net/weixin_53499537/article/details/146534151  浏览:    关键词:【R语言可视化】人口金字塔
# 安装并加载包
install.packages("ggplot2")
library(ggplot2)# 示例数据-可替换
population <- data.frame(age_group = rep(c("0-4", "5-9", "10-14", "15-19", "20-24","25-29", "30-34", "35-39", "40-44", "45-49","50-54", "55-59", "60-64", "65-69", "70-74","75-79", "80+"), 2),gender = rep(c("Male", "Female"), each = 17),population = c(-500, -600, -700, -800, -1000, -1100, -1200, -1300,-1100, -1000, -900, -800, -700, -600, -400, -300, -200,480,  580,  680,  750,  950, 1050, 1150, 1200,1100, 1000, 900, 850, 750, 600, 500, 400, 300))# 年龄段因子排序(按从小到大)
population$age_group <- factor(population$age_group,levels = rev(c("0-4", "5-9", "10-14", "15-19", "20-24", "25-29", "30-34", "35-39", "40-44", "45-49", "50-54", "55-59", "60-64", "65-69", "70-74", "75-79", "80+")))# 绘制金字塔图
ggplot(population, aes(x = age_group, y = population, fill = gender)) +geom_bar(data = subset(population, gender == "Male"), stat = "identity", width = 0.7) +geom_bar(data = subset(population, gender == "Female"), stat = "identity",width = 0.7) +coord_flip() +scale_y_continuous(labels = abs, breaks = seq(-1500, 1500, 500)) +scale_fill_manual(values = c("Male" = "#1f77b4", "Female" = "#ff7f0e")) +labs(title = "", x = "Age Group",  y = "Population", fill = "Gender") +theme_bw()+theme(text=element_text(family="Times New Roman"),legend.position = c(0.9, 0.9),  # 图例相对坐标,右上角legend.background = element_rect(fill = "white", color = "gray80", size = 0.1),legend.title = element_text(face = "bold"),axis.ticks.length = unit(-0.1, "cm"),   # 坐标刻度向内,负值 = 向内axis.ticks = element_line(color = "black"),panel.grid.major.y = element_blank(),  # 去除横向网格线panel.grid.minor.y = element_blank(),panel.grid.major.x = element_blank(),  # 去除横向网格线panel.grid.minor.x = element_blank())

结果展示:

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词