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

结果展示:

相关推荐
Interview Aid1125 小时前
TikTok OA 四题分享|半小时内 AC,题目基本都是实现题
java·开发语言·算法·面试·职场和发展
CoderIsArt13 小时前
C#中UI 线程与 Dispatcher
开发语言·ui·c#
AI情绪识别开源15 小时前
检信 ALLEMOTION OS 加密打包可执行程序 — 全面测试报告版本: v1.3功能测试 / 性能测试 /
开发语言·数据结构·人工智能·功能测试
「QT(C++)开发工程师」16 小时前
C++ auto 用法详解
开发语言·c++
OPEN-F16 小时前
C++STL教程:容器适配器与实用工具
开发语言·c++
yaoxin52112317 小时前
507. Java 反射 - 在 BeanFactory 中实现依赖注入
java·开发语言
OPEN-F17 小时前
C++模板教程:变参模板、折叠表达式与SFINAE
java·开发语言·c++
有点。17 小时前
C++二叉搜索树进阶
开发语言·c++
HugoStudio_SWAN17 小时前
【擦除重绘】C++ 控制台动画:弹跳 Logo DVD 屏保效果
开发语言·c++·学习·程序人生