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

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())

结果展示:

相关推荐
阿里嘎多学长4 小时前
2026-09-20 GitHub 热点项目精选
开发语言·程序员·github·代码托管
weixin_307779135 小时前
C++代码实现MATLAB中的ode23tb函数功能
开发语言·c++·算法·matlab
2601_966949656 小时前
为什么量化回测中 for 循环比 DataFrame 慢三个数量级?从向量化原理讲起
开发语言·python·pandas·股票数据·quantdash
边境悍匪7 小时前
蜗牛学苑 Java 智能体学习 Day45|Knife4j+SpringBoot3、书城项目整合 MyBatis 思维导图复盘
java·开发语言·vue.js·学习·spring
我的xiaodoujiao7 小时前
Django 基础知识详细图文教程 9-Django 模板引擎 2
开发语言·数据库·后端·django
菜鸟~noob2337 小时前
【太空电子战】从CCS到Meadowlands:反通信系统的二十年演进史【含matlab代码】
开发语言·matlab
quantdash_cc8 小时前
量化策略为什么需要实时行情数据?从信号产生到交易决策的时间差说起
开发语言·python·数据分析·量化交易·股票数据·quantdash
逆向编程10 小时前
QGIS地图投影(CRS坐标参照系)设置
开发语言
free-elcmacom10 小时前
发际线警告!手撕《C陷阱与缺陷》终极 BOSS:signal 函数与 typedef 魔法
c语言·开发语言·visual studio code·visual studio
程序员阿鹏10 小时前
简单介绍一下软引用
java·开发语言·jvm·数据结构·后端