1

I was using R to plot the graph using JRI. I used the below code:

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

And calling the generated file from the jsp using

 <\img src='<filename>'/>

Instead of saving and calling the file in "img" tag, is it possible to plot the graph dynamically? I want to display the graph in the browser. Please suggest.

1 Answer 1

1

You can use data URIs and inline the graphics:

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))

As noted, you can output the png (or jpeg in your case) to a tempfile/dir and (optionally) remove that when done.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I am able to generate the graph in the browser. My main concern was, since its an JSP, what if 100 users are using the JSP, then the value for x and y will change(based on users). So, if I am saving the plot in a file (myplot.png), it will get overwritten by other user's data. So, I was looking for a way not to save in a file and pull data, instead just display in a browser on the fly.
Thanks. Is it possible to open it in the same tab, it opens in a new tab.
You probably don't want to use htmltools::html_print(htmltools::HTML(encoded_png)) in your code. You just want the <img…/> string printed since it's JSP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.