簡體   English   中英

在R中循環tempfile()

[英]looping tempfile() in r

我不知道為什么這是錯誤的。 我基本上是在嘗試使用ggplot在HTML模板上創建進度條。 為此,我需要創建一個for循環並將其存儲在r中的temp文件夾中。 然后將png文件編碼為base64格式,以便我可以將其放在HTML圖像標簽上。

library(catools)

a <- seq(1:10)
1:length(a)

for (i in 1:length(a)){

total_questions <- 8
current_question<- i+1

group <- rbind("Total Questions", "Current question")
progress <- rbind(total_questions, current_question)
colnames(progress)<- "Progress"
progress <- as.data.frame(progress)
progress_bar <- cbind(group,progress)


# save example plot to file

png(tec <- tempfile(paste0("image",i), fileext = ".png"))
ggplot(progress_bar, aes(group, Progress,fill=group), height=1000, width=800) + geom_histogram(stat="identity") 
dev.off()
# Base64-encode file
txt <- base64Encode(readBin(tec, "raw", file.info(tec)[1, "size"]), "txt")
txt
}

這是我的錯誤。

file(con,“ rb”)中的錯誤:無法打開連接另外:警告消息:在file(con,“ rb”)中:無法打開文件'/ var / folders / w0 / lrdx2zvn2hgf_ds0f92hpy500000gn / T // RtmpWD4Ysl / image114459476144 .png':沒有這樣的文件或目錄

您可以改用ggsave 它可以保存任何ggplot2圖,默認為最后一個。 它根據提供的文件路徑的擴展名自動檢測要寫入的文件類型(此處為.png)。

另外,手動設置大小(寬度和高度)可以使您更可靠地保存繪圖(否則,繪圖大小是當前未設置的png設備的大小,默認為繪圖屏幕的當前大小) IIRC)。

tec <- tempfile(paste0("image",i), fileext = ".png")
p <- ggplot( // your plot here // ) 
ggsave(tec, p, width=5, height=5)

仔細選擇大小,因為它會對字體大小產生很大影響。 如果您在使用時需要5x5的圖像,則保存為10x10將導致裁切后的文本小兩倍。 如果您需要10x10的圖像,將其保存到5x5將會很丑陋。

如果您正在開發某種需要進度條圖像的軟件,則可能需要將圖像另存為pdf,以便任何尺寸的圖像看起來都不錯。

所以這對我來說很好。 我能夠創建每個圖並將其保存到一個臨時文件中,然后繼續獲取base64代碼,然后將其鏈接到html中的圖像標簽。 因此,每當該人單擊下一個問題時,新網頁中的條形圖將增加i。

require(grid) 
require(ggplot2)

a <- seq(1:10)
for(i in 1:length(a)){
total_questions <- 10
current_question<- i

group <- rbind("Total Questions", "Current question")
progress <- rbind(total_questions, current_question)
colnames(progress) <- "Progress"
progress <- as.data.frame(progress)
progress_bar <- cbind(group,progress)

# save example plot to file
png(tec <- tempfile(fileext = ".png"), height=200, width=300)
p <- ggplot(progress_bar, aes(group, Progress,fill=group)) +     geom_histogram(stat="identity") + coord_flip() + xlab("") + ylab("") + theme(legend.position="none") 
gt <- ggplot_gtable(ggplot_build(p))

# plot table without spacing. 
ge <- subset(gt$layout, name == "panel")
grid <- grid.draw(gt[ge$t:ge$b, ge$l:ge$r])
dev.off()

# Base64-encode file
library(RCurl)
txt <- base64Encode(readBin(tec, "raw", file.info(tec)[1, "size"]), "txt")
txt
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM