首页 > 解决方案 > 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) 
} 

那是行不通的!有什么建议么?

标签: rloopsggplot2

解决方案


使用 和 的组合lapplyaes_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())
}

推荐阅读