1

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

j_3265
  • 207
  • 3
  • 12
  • 2
    Could you make a minimum working example with example data so we can reproduce the problem? – Ryan Oct 25 '19 at 05:07
  • Could it be that you're reading in data.table as df but you're running gbm on train that's causing the problem? – TheN Oct 25 '19 at 08:09
  • I think @TheN identified the problem.. – StupidWolf Oct 25 '19 at 08:28
  • 2
    `vip` seems to use `ggplot`-based graphics, so perhaps you need to `print` the vip object (see https://stackoverflow.com/questions/26034177/save-multiple-ggplots-using-a-for-loop) – BenBarnes Oct 25 '19 at 10:45
  • @BenBarnes thanks! I managed to solve the problem. The solution was to use ggsave! Thanks for the link. – j_3265 Oct 26 '19 at 01:23
  • @BenBarnes I would like to finalize the question, could you post as an answer to give you credit as a solution? – j_3265 Nov 13 '19 at 19:43

1 Answers1

2

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)
BenBarnes
  • 19,114
  • 6
  • 56
  • 74