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

结果展示:

相关推荐
郑州光合科技余经理6 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1236 天前
matlab画图工具
开发语言·matlab
dustcell.6 天前
haproxy七层代理
java·开发语言·前端
norlan_jame6 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone6 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054966 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月6 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237176 天前
C语言-数组练习进阶
c语言·开发语言·算法
Railshiqian6 天前
给android源码下的模拟器添加两个后排屏的修改
android·开发语言·javascript
雪人不是菜鸡6 天前
简单工厂模式
开发语言·算法·c#