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

结果展示:

相关推荐
星落梦生5 小时前
SpringAOP基础笔记(7)
java·开发语言
曹牧7 小时前
Java:“刷新雪崩”
java·开发语言
郝学胜-神的一滴7 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
西西弗Sisyphus8 小时前
C++ explicit 关键字工程实践
开发语言·c++
郝学胜-神的一滴9 小时前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
feixing_fx10 小时前
原始类型与引用类型:赋值时到底复制了什么
开发语言·前端·javascript·前端框架
wuyk55510 小时前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel
神明不懂浪漫11 小时前
【第八章】多线程(一)
java·开发语言·经验分享·笔记
yiangL_11 小时前
1、Python 输入输出实验|print 与 input 人机交互实践
开发语言·python·人机交互
山楂树の14 小时前
Java 泛型:泛型类、泛型方法、泛型接口与通配符
java·开发语言·笔记