在 r 中循环 tempfile()

looping tempfile() in r

我不确定为什么这是错误的。我基本上是在尝试使用 ggplot 在 HTML 模板上创建进度条。为此,我需要创建一个 for 循环并将其存储在 r 中的临时文件夹中。然后将 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
}

这是我的错误。

Error in file(con, "rb") : cannot open the connection In addition: Warning message: In file(con, "rb") : cannot open file '/var/folders/w0/lrdx2zvn2hgf_ds0f92hpy500000gn/T//RtmpWD4Ysl/image114459476144.png': No such file or directory

您可以改用 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 代码,随后 link 将其添加到 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
}