java - 使用 JRI 从 JSP 动态绘制 R 图

标签 java r jsp jri

我使用 R 来使用 JRI 绘制图表。我使用了以下代码:

Rengine re = new Rengine (new String [] {"--vanilla"}, false, null);
re.eval("jpeg('<filename>')";
re.eval("plot(x,y)");
re.eval("dev.off()");

并使用

从 jsp 调用生成的文件
 <\img src='<filename>'/>

是否可以动态绘制图形,而不是在“img”标签中保存和调用文件?我想在浏览器中显示图表。 请提出建议。

最佳答案

您可以使用data URIs并内联图形:

library(base64enc)

# unique filename; you can specify tmpdir for the 
# location where the png will be written
this_file <- tempfile("supercoolplot", fileext=".png")

# make a png
png(file=this_file <- tempfile("supercoolplot", fileext=".png"), width=200, height=200, bg="transparent")
plot(sample(1:10, 10, replace=TRUE)) # randomize plot
rect(1,5,3,7,col="white")
dev.off()

# show you the file
print(this_file)

# encode the png
encoded_png <- sprintf("<img src='data:image/png;base64,%s'/>", base64encode(this_file))

# optionally remove the offending file
# if you use the tmpdir option then you can prbly leave the
# file there and serve it up via the <img/> tag directly
# vs encode it below
unlink(this_file)

# see what we did (only showing part of the string)
substr(encoded_png, 1, 80)

## [1] "<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAD"

# prove it works (run this in your R Console / RStudio
htmltools::html_print(htmltools::HTML(encoded_png))

如上所述,您可以将 png(或您的情况下的 jpeg)输出到临时文件/目录,并(可选)在完成后将其删除。

关于java - 使用 JRI 从 JSP 动态绘制 R 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32065365/

相关文章:

java - 带 Spring @Async 注解的方法未执行

Java 泛型 : How to create a to-n collection with configurable value holder type

java - Eclipse 中的 JSP 页面指令格式

java - WAS 6.1 显示 Java 版本 5,但实际上是 1.4

javascript - sweetAlert 在 jsp 页面内无法正常工作

java - 什么是NullPointerException,我该如何解决?

java - 使用 X.new Y() 实例化对象意味着什么?

r - 使用 {tibble} 中的 enframe 将 tibble 中的列表列转换为多列

r - 如何在 ggplot/R 中制作这个直方图?

r - 在r中的栅格层上绘制空间点