You need to enable JavaScript to run this app. 如何用R语言ggplot循环从单CSV生成各建筑独立线图
优惠活动
大模型
产品
解决方案
定价
更多

如何用R语言ggplot循环从单CSV生成各建筑独立线图

问题根源
  • 循环直接遍历d_long$Name会按数据行重复执行,每个建筑对应多少行就重复生成多少次相同文件,无法仅遍历一次唯一建筑标识
  • 绘图时直接传入全量数据集d_long,未筛选当前迭代对应的建筑子集,因此所有图表内容完全一致
修正后可运行代码
# 加载依赖包
library(tidyverse)
library(lubridate)

# 读取原始数据
d <- read_csv("res_data_ABC.csv")

# 数据清洗转换
d_long <- d %>%
  pivot_longer(cols = -Name, names_to = "date", values_to = "n") %>%
  na.omit() %>%
  # 字符型日期转标准日期格式,避免X轴排序错乱
  mutate(date = mdy(date))

# 自动创建输出目录(避免目录不存在时报错)
dir.create("~/Desktop/plots", showWarnings = FALSE, recursive = TRUE)

# 提取唯一建筑名列表,避免重复迭代
unique_buildings <- unique(d_long$Name)

# 循环生成单建筑图表
for (curr_bldg in unique_buildings) {
  # 筛选当前建筑的专属数据集
  sub_df <- d_long %>% filter(Name == curr_bldg)
  
  # 基于子集绘图
  plot_obj <- ggplot(sub_df, aes(x = date, y = n)) +
    geom_line(linewidth = 1) +
    geom_point(size = 2) +
    ggtitle(curr_bldg) +
    ylab("viral density/L") +
    theme_bw() +
    theme(
      axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold")
    )
  
  # 保存对应图片
  ggsave(
    filename = paste0("~/Desktop/plots/", curr_bldg, ".png"),
    plot = plot_obj,
    width = 6,
    height = 5,
    units = "cm",
    dpi = 300
  )
}
特殊场景适配说明
  • 若建筑名包含特殊字符(如斜杠、冒号)导致文件保存报错,可将文件名生成逻辑替换为:paste0("~/Desktop/plots/", str_replace_all(curr_bldg, "[[:punct:]]", "_"), ".png"),自动把特殊字符替换为下划线
  • 若无需调整日期格式,可删除mutate(date = mdy(date))行,但字符型日期易出现X轴顺序与实际时间不符的问题,不建议删除

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.23 06:15:06