r - 在 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")
}
我可以获得适用于所有系统的代码,但我无法为每个系统创建单独的图表: 此图表显示氨如何随季节在所有系统中的所有池塘的深度变化。
提前感谢您提供的任何帮助!
解决方案
实现所需结果的一种选择是将数据参数添加到函数 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]]
推荐阅读
- javascript - 即使用户已登录,Firebase javascript auth 用户仍显示 null
- generics - 在 Rust 中,我需要什么特征来比较泛型和整数
- flutter - 如何从字符串导入随机生成的 4096 位 Java RSA 公钥
- machine-learning - SVM 中的网格搜索根本没有改进模型
- reactjs - 将流式值设置为 React 状态
- python - 小于 < 符号不适用于日期 pandas python
- amazon-web-services - 带有 Kinesis 流 2 个分片的 AWS Lambda
- html - 如何让刻度转到短文本行的左侧(见截图) HTML & CSS
- javascript - 是否可以在输入元素上使用多种类型属性
- c# - 使用 IIS 的 Asp.Net Core API 响应错误的 json 编码