简体   繁体   中英

Loop in R using paste to plot graphs

Graphics come out blank.

I need to plot several graphs from a GBM analysis, so I am using a loop along with the paste function.

But are all the graphics coming out blank? What can it be? When executing code out of the loop everything works. Thank you

list <- list("A","B", "C")

for (i in list) {

df <- fread(paste("data_", i, ".csv", sep = ""), header = TRUE)

gbm.fit <- gbm( formula = y ~ ., distribution = "gaussian", data = train,n.trees = 1000, interaction.depth = 5, shrinkage = 0.1, cv.folds = 5, n.cores = NULL, verbose = FALSE )

pathname <- paste("gbm", i, ".tiff", sep = "")
tiff( file = pathname, width = 1200, height = 1000, res = 105 )

vip( gbm.fit, num_features = 15, bar = TRUE, width = 0.75, horizontal = TRUE, color = hcl.colors( 15, palette = "Greens2", alpha = NULL, rev = FALSE, fixup = TRUE ), fill = hcl.colors( 15, palette ="Greens", alpha = NULL, rev = TRUE, fixup = TRUE ) )

dev.off()

}

I would like the graphics to come out with the correct content

The vip function uses ggplot2 -based graphics. Therefore, either print() the plot or use ggsave() to save the plot to a file:

1. The print() method:

myPlot <- vip( gbm.fit, num_features = 15, bar = TRUE, width = 0.75, horizontal = TRUE, 
  color = hcl.colors( 15, palette = "Greens2", alpha = NULL, rev = FALSE,
  fixup = TRUE ), fill = hcl.colors( 15, palette ="Greens", alpha = NULL,
  rev = TRUE, fixup = TRUE ) )

tiff( file = pathname, width = 1200, height = 1000, res = 105 )
print(myPlot)    
dev.off()

2. The ggsave() method:

myRes <- 105 # ggsave uses inches, not pixels
ggsave(pathname, myPlot, device = "tiff", width = 1200 / myRes,
  height = 1000 / myRes, dpi = myRes)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM