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

使用ggplot2过滤数据绘制分年龄组3×3折线子图的实现问题

R语言ggplot2多分组3×3折线图实现

问题描述

现有包含year、age、data三个变量的数据集,共9个不同年龄组,需要生成3×3布局的折线图,每个子图仅展示对应年龄组的年度变化趋势。
最初采用循环生成子图再拼接的方案时,所有子图都展示了全部年龄组的折线,未实现按年龄组过滤数据的效果。

原有问题代码

# n is a list of unique values aka age groups in the Data1
n <- unique(Data1$age)  

# Preparation for plotting all subplots    
plot_lst <- vector("list", length = length(n))

for (i in 1:length(n)) {
  g <- ggplot(Data1, aes(x=year, y=data, color=age)) +
    geom_line()
  plot_lst[[i]] <- g
}

# Plotting all subplots into one
cowplot::plot_grid(plotlist = plot_lst, ncol = 3)

最终解决方案

无需手动循环生成子图,直接使用ggplot2内置的facet_wrap()分面功能即可自动按年龄组拆分数据、生成对应子图,也可手动指定ncol参数固定3列布局:

ggplot(Data1, aes(year, data)) +
  geom_line() +
  geom_point() +
  facet_wrap(~ age, ncol = 3)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:54:02