簡體   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