在R中使用循环时无法保存图形

dbf7pr2w  于 2022-12-06  发布在  其他
关注(0)|答案(3)|浏览(242)

由于某种原因,我不明白,为什么当我运行一个ggplot循环来创建多个图表时,我在环境中看不到它们,因此无法进一步显示图表。

db = data.frame(exposure = sample(1:100, 100),
                   exposure2 = sample(-90:100,100),
                   outcome = sample(200:1000,100))

exposure_vector = c("exposure","exposure2")
exposure_title = c("Pesticide","Apple")
for (i in 1:length(exposure_vector)) {
  current_exposure = db[[exposure_vector[i]]]
  title = exposure_title[i]
  graph_name = paste0(title,"_","Graph")
  graph_name=ggplot(db,aes(x=current_exposure,y=outcome))+geom_smooth()+
    theme_bw()+ylab("outcome")+xlab("exposure")+ggtitle(title)
  print(graph_name)
  
  
}
idfiyjo8

idfiyjo81#

这可能是一个更好的方法来完成你要做的事情。你可以对你的标题和曝光向量进行mapply,它将返回一个list的图表,你可以通过名称来引用它:
第一个

graphs$Apple

mctunoxg

mctunoxg2#

graphname超出范围。
您需要在循环外声明它。
比如说

db = data.frame(exposure = sample(1:100, 100),
                exposure2 = sample(-90:100,100),
                outcome = sample(200:1000,100))

exposure_vector = c("exposure","exposure2")
exposure_title = c("Pesticide","Apple")

plot <- list() #declare
for (i in 1:length(exposure_vector)) {
  current_exposure = db[[exposure_vector[i]]]
  title = exposure_title[i]
  graph_name = paste0(title,"_","Graph")
  graph_name=ggplot(db,aes(x=current_exposure,y=outcome))+geom_smooth()+
    theme_bw()+ylab("outcome")+xlab("exposure")+ggtitle(title)
  
  plot[[i]] <- graph_name #write
  print(graph_name)
  
  
}
6yjfywim

6yjfywim3#

我假设你想给变量paste0(title, "_", "Graph")赋值,如果这是正确的,你应该使用assign

library(ggplot2)

db <- data.frame(exposure = sample(1:100, 100),
                 exposure2 = sample(-90:100,100),
                 outcome = sample(200:1000,100))

exposure_vector <- c("exposure","exposure2")
exposure_title <- c("Pesticide","Apple")

for (i in 1:length(exposure_vector)) {
  current_exposure <- db[[exposure_vector[i]]]
  title <- exposure_title[i]
  graph_name <- paste0(title,"_","Graph")
  p <- ggplot(db,aes(x=current_exposure,y=outcome))+
      geom_smooth()+
      theme_bw()+
      ylab("outcome")+
      xlab("exposure")+
      ggtitle(title)
  
  assign(graph_name, p)
  print(p)
}

ls()

##> [1] "Apple_Graph"      "current_exposure" "db"               "exposure_title"  
##> [5] "exposure_vector"  "graph_name"       "i"                "p"               
##> [9] "Pesticide_Graph"  "title"

相关问题