R-使用ggplot2循环,按列名存储绘图
我有这样一个数据帧:R-使用ggplot2循环,按列名存储绘图,r,loops,ggplot2,R,Loops,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
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)
}
那不行!有什么建议吗?使用lappy和aes_字符串的组合,我们可以生成绘图列表。然后,如果需要,可以按名称提取列表的每个组件
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
这可能不是最好的方法,但您可以尝试使用递归
f <- colnames(testframe)
sotc <- function(x){
if(is.na(f[x])){return()}
else
{ assign(paste0("p_",f[x]),
ggplot(testframe,aes_string(f[1],f[x]))+geom_line(),envir = globalenv())}
sotc(x+1)
}
sotc(2)
p_ABC
f <- colnames(testframe)
sotc <- function(x){
if(is.na(f[x])){return()}
else
{ assign(paste0("p_",f[x]),
ggplot(testframe,aes_string(f[1],f[x]))+geom_line(),envir = globalenv())}
sotc(x+1)
}
sotc(2)
p_ABC