[英]Loop in R to create and save series of ggplot2 plots with specified names
[英]R - Loop with ggplot2, storing plots by column-names
我有一個這樣的數據框:
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())
}
這可能不是最好的方法,但是您可以嘗試遞歸。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.