You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于R语言绘制按年龄组划分的社会经济地位人群百分比折线图

在R语言中绘制符合Excel样式的年龄组-社会经济地位百分比折线图

步骤1:准备示例数据

先构造模拟的示例数据框(如果已有真实数据,直接替换即可):

library(tibble)
df <- tibble(
  AgeGroup = rep(c("18-24", "25-34", "35-44", "45-54", "55-64", "65+"), each = 5),
  SocioEconomicStatus = rep(1:5, 6),
  Percentage = c(
    22, 20, 18, 25, 15,
    18, 22, 20, 24, 16,
    15, 21, 23, 22, 19,
    12, 19, 25, 24, 20,
    10, 17, 26, 27, 20,
    8, 15, 28, 29, 20
  )
)

步骤2:用ggplot2绘制Excel风格折线图

使用ggplot2包实现,还原Excel默认折线图的核心样式(带数据点、百分比标签、清晰网格和高区分度配色):

library(ggplot2)

ggplot(df, aes(x = AgeGroup, y = Percentage, group = SocioEconomicStatus, color = factor(SocioEconomicStatus))) +
  # 绘制折线并设置粗细
  geom_line(linewidth = 1) +
  # 添加数据点提升辨识度
  geom_point(size = 3) +
  # 在数据点上方添加百分比标签
  geom_text(aes(label = paste0(Percentage, "%")), vjust = -0.8, size = 3.5) +
  # 使用高区分度的配色方案
  scale_color_brewer(palette = "Set1") +
  # 设置坐标轴和图表标题
  labs(
    x = "年龄组",
    y = "人群百分比",
    color = "社会经济地位",
    title = "各年龄组不同社会经济地位人群占比"
  ) +
  # 调整主题贴近Excel风格
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.5, size = 14, face = "bold"),
    axis.title.x = element_text(size = 12),
    axis.title.y = element_text(size = 12),
    legend.title = element_text(size = 11),
    panel.grid.major = element_line(color = "#e0e0e0"),
    panel.grid.minor = element_blank()
  ) +
  # 设置Y轴范围和刻度,适配数据区间
  scale_y_continuous(limits = c(0, 35), breaks = seq(0, 35, 5))

关键细节说明

  • group = SocioEconomicStatus:确保每个社会经济地位类别单独生成一条折线
  • geom_point和geom_text:还原Excel折线图常带数据点和标签的设计,方便直接读取具体数值
  • 主题调整:通过theme修改网格线颜色、标题样式,贴近Excel的简洁视觉风格
  • 配色方案:scale_color_brewer生成的颜色区分度高,避免不同折线混淆

内容的提问来源于stack exchange,提问作者Usman YousafZai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 13:12:48