繁体   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