r - R - 使用 ggplot2 循环,按列名存储图
问题描述
我有一个这样的数据框:
date_list = seq(ymd('2000-01-01'),ymd('2000-12-31'),by='day')
testframe = data.frame(Date = date_list)
testframe$ABC = rnorm(366)
testframe$DEF = rnorm(366)
testframe$GHI = seq(from = 10, to = 25, length.out = 366)
testframe$JKL = seq(from = 5, to = 45, length.out = 366)
我想自动化我在下面做的事情。我想根据时间(日期)从 2:4 开始绘制每一列。绘图应以 p_columnname 之类的形式保存。
p_ABC = ggplot(data = testframe, aes(x = Date, y = ABC)) +
geom_line(color = "grey", size = 1)
p_DEF = ggplot(data = testframe, aes(x = Date, y = DEF)) +
geom_line(color = "grey", size = 1)
p_GHI = ggplot(data = testframe, aes(x = Date, y = GHI)) +
geom_line(color = "grey", size = 1)
p_JKL = ggplot(data = testframe, aes(x = Date, y = JKL)) +
geom_line(color = "grey", size = 1)
我试图创建一个循环:
library(ggplot2)
theme_set(theme_gray())
for (i in colnames(testframe[2:ncol(testframe)])) {
paste("p", i, sep = "_") = ggplot(data = testframe, aes(x = Date, y = i)) +
geom_line(color = "grey", size = 1)
}
那是行不通的!有什么建议么?
解决方案
使用 和 的组合lapply
,aes_string
我们可以生成绘图列表。然后,如有必要,您可以按名称提取列表的每个组件。
plot_list <- lapply(names(testframe)[-1],
FUN = function(n)
ggplot(testframe, aes_string("Date", n))+geom_line())
names(plot_list) <- paste0("p_", names(testframe)[-1])
plot_list$p_ABC
如果您想坚持使用for
循环框架,我们可以使用该assign
功能:
for(n in names(testframe)[-1]){
assign(paste0("p_", n),
ggplot(testframe, aes_string("Date", n))+
geom_line())
}
推荐阅读
- javascript - 如何打开一个持久的 SSH 客户端来制作一个基于 Web 的文件管理器?
- powershell - PowerShell Remove-Item 排除文件夹文件
- java - 将 Redis 集成到 JHipster CacheConfiguration 错误
- c# - C# WinForms 崩溃,没有异常
- aerospike - Aerospike 中自定义 Java 对象的二级索引
- swift - 如何从模型数组中随机化卡片数据而不重复
- python - 是否可以使用 Windows DSN 通过 sqlalchemy 连接到 postgresql?
- java - 如何在 Spring Data Rest 上的 GET/find 中对实体进行计算?
- sql - 多个查询的结果在 Oracle 中作为一个结果
- reactjs - Typescript Type 或 Lint 以防止意外地将实际函数渲染到 JSX 中,而不是执行的返回值