繁体   English   中英

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

[英]Loop in R using paste to plot graphs

图形出现空白。

我需要 plot 来自 GBM 分析的几个图表,所以我使用循环和粘贴 function。

但是所有的图形都是空白的吗? 会是什么? 在循环外执行代码时,一切正常。 谢谢

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

}

我希望图形带有正确的内容

vip function 使用基于ggplot2的图形。 因此,要么print() plot 要么使用ggsave()将 plot 保存到文件中:

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. 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