簡體   English   中英

在 R 中使用循環時無法保存 ggplot 圖

[英]Cant save ggplot graphs while using a loop in R

出於某種原因,我無法弄清楚,為什么當我運行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)
  
  
}

這可能是做你想做的事情的更好方法。 你可以mapply你的標題和曝光向量,這將返回一個圖表list ,然后你可以按名稱引用:

graphs <- mapply(X=exposure_title,Y=exposure_vector, function(X,Y){
  
  ggplot(db,aes(x=.data[[Y]],y=outcome))+
    geom_smooth()+
    theme_bw()+
    ylab("outcome")+
    xlab("exposure")+
    ggtitle(X)

}, SIMPLIFY = FALSE )
graphs$Pesticide

在此處輸入圖像描述

graphs$Apple

在此處輸入圖像描述

graphname超出 scope。

您需要在循環外聲明它。

例如

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)
  
  
}

我假設你想分配給一個名稱為paste0(title, "_", "Graph")的變量,即 plot 的值。如果這是正確的,你應該使用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"           

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM