当前位置: 首页 > article >正文

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

结果展示:


http://www.kler.cn/a/611029.html

相关文章:

  • 游戏引擎学习第183天
  • 7.5 窗体事件
  • 如何理解FFMPEG两个宏 1.MATCH_PER_TYPE_OPT, 2.MATCH_PER_STREAM_OPT
  • 【Python】编程50个经典操作
  • 图解神经网络和强化学习
  • 回滚日志(Undo Log) 的 Purge
  • 【SpringCloud】认识微服务
  • JVM类加载过程详解
  • 【Python-OpenCV】手势控制贪吃蛇
  • Linux系统管理与编程08:任务驱动综合应用
  • 音视频 三 看书的笔记 MediaPlayer的C/S架构
  • 基于LLM的Agent框架全面比较分析:MGX(MetaGPT X)、AutoGen、OpenHands与秒哒(MiaoDa)
  • WMS WCS系统架构
  • MongoDB 实际工作中应用场景
  • ctfshow WEB web3
  • Conda常用命令汇总(持续更新中)
  • jmeter接口自动化+ant执行(方案)
  • Maven插件学习(二)——测试插件maven-surefire-pluigin
  • Redis原理:watch命令
  • ReentrantLock 锁优化与 synchronized 锁膨胀的共同点