首页 > 解决方案 > 在 R 的 for 循环中自动绘制嵌套数据帧

问题描述

我正在寻求帮助在 R 中导航和可视化一个巨大的实地研究数据集。我想自动可视化数据的子集。我的实地研究涉及跨季节(因子)从多池塘系统(因子)中的不同池塘(因子)采集的各种样本(数字)。我想根据池塘(在考虑的系统内)和颜色按季节绘制每个池塘系统的各种数字测量值(x)如何随深度(y)变化。

为此,我认为我需要使用“nest:”压缩每个池塘系统的数据:

    comp_nested <- comp %>% group_by(System) %>% nest()        

这就是嵌套数据框的样子

我遇到困难的地方是访问每个系统的嵌套数据以在 for 循环中绘制感兴趣的参数:

for (i in comp_nested$System) {
  
unnested <- unnest(comp_nested[2], as_df)
str(unnested)

scatter_fun = function(x, y) {
     ggplot(unnested, aes(x = .data[[x]], y = .data[[y]], color=Season, shape=Pond, size=0.5) ) +
    scale_y_reverse()+
          geom_point() +
  theme(axis.text = element_text(size = 10), panel.background=element_rect(fill="white", color="black"))+
  theme(legend.key=element_rect(fill="white"), legend.title= element_text(size=10), legend.text=element_text(size=10))+
  guides(size=FALSE)+
  guides(color = guide_legend(override.aes = list(size = 2)), shape=guide_legend(override.aes = list(size = 2)))
}

scatter_fun(x="Ammonia_N", y="Depth_in")
}

我可以获得适用于所有系统的代码,但我无法为每个系统创建单独的图表: 此图表显示氨如何随季节在所有系统中的所有池塘的深度变化。

提前感谢您提供的任何帮助!

标签: rfor-loopggplot2nested

解决方案


实现所需结果的一种选择是将数据参数添加到函数 a 以遍历嵌套数据集的数据列。

使用mpg数据集作为示例数据:

library(ggplot2)
library(tidyr)
library(dplyr)

scatter_fun <- function(.data, x, y) {
  ggplot(.data, aes(x = .data[[x]], y = .data[[y]], color = manufacturer, shape = cyl)) +
    scale_y_reverse() +
    geom_point(size = 2) +
    theme(axis.text = element_text(size = 10), panel.background = element_rect(fill = "white", color = "black")) +
    theme(legend.key = element_rect(fill = "white"), legend.title = element_text(size = 10), legend.text = element_text(size = 10)) +
    guides(color = guide_legend(override.aes = list(size = 2)), shape = guide_legend(override.aes = list(size = 2)))
}

mpg_nested <- mpg %>% 
  mutate(cyl = factor(cyl)) %>% 
  nest(data = -class)

foo <- lapply(mpg_nested$data, function(x) scatter_fun(x, "cty", "hwy"))

foo[[1]]

foo[[2]]


推荐阅读