简体   繁体   English

在 R 中循环使用粘贴到 plot 图表

[英]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.我需要 plot 来自 GBM 分析的几个图表,所以我使用循环和粘贴 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. vip function 使用基于ggplot2的图形。 Therefore, either print() the plot or use ggsave() to save the plot to a file:因此,要么print() plot 要么使用ggsave()将 plot 保存到文件中:

1. The print() method: 1. print()方法:

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: 2. ggsave()方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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