如何在ggplot子图的X轴标题或副标题中显示对应数据框名称
给ggplot子图添加对应数据框名称的解决方法
问题根源
你用lapply遍历数据框列表时,function(x)里的x是单个数据框对象,names(x)返回的是该数据框的列名,而非列表中这个元素的名称(A5/B5/K1),所以拿不到想要的标题文本。
三种可行方案
方案1:用Map同时遍历名称和数据框
Map可以同时传递列表的名称和对应的数据框,直接在绘图函数里调用名称:
co_gpl <- Map(function(df_name, df) { ggplot(df) + geom_line(aes(x = `Time`, y = get(names(df[grep("temp", colnames(df))]))), color = "red3", size = 0.3) + labs(y = "Temperatura [°C]", x = df_name) # 将数据框名称设为X轴标题,也可以用subtitle=df_name设为副标题 theme(axis.text.x = element_text(angle = 90, vjust = 0.5), legend.position = "top", legend.justification = "center") }, names(co_lst2), co_lst2) ggp <- wrap_plots(co_gpl, nrow = 1, ncol = 3) ggp
方案2:合并数据框+分面(更简洁高效)
把所有数据框合并成一个大表,新增一列标记来源名称,用facet_wrap自动生成带标题的子图:
library(dplyr) library(tidyr) # 合并数据并添加来源列 combined_df <- bind_rows(co_lst2, .id = "Source") %>% pivot_longer(cols = contains("temp"), names_to = "Metric", values_to = "Temperature") # 绘制分面图 ggplot(combined_df, aes(x = Time, y = Temperature)) + geom_line(color = "red3", size = 0.3) + facet_wrap(~Source, nrow = 1, ncol = 3) + # 按来源名称分面,自动显示标题 labs(y = "Temperatura [°C]") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5), legend.position = "top", legend.justification = "center")
方案3:沿用lapply,通过索引获取名称
如果不想改遍历方式,也可以通过列表索引来提取对应名称:
co_gpl <- lapply(seq_along(co_lst2), function(i) { df_name <- names(co_lst2)[i] df <- co_lst2[[i]] ggplot(df) + geom_line(aes(x = `Time`, y = get(names(df[grep("temp", colnames(df))]))), color = "red3", size = 0.3) + labs(y = "Temperatura [°C]", x = df_name) + theme(axis.text.x = element_text(angle = 90, vjust = 0.5), legend.position = "top", legend.justification = "center") }) ggp <- wrap_plots(co_gpl, nrow = 1, ncol = 3) ggp
内容的提问来源于stack exchange,提问作者GrBa
相关产品推荐
相关产品推荐

