# 安装并加载包
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())
结果展示: