Created
January 11, 2015 01:49
-
-
Save pgtwitter/f798065644e4630ac55a to your computer and use it in GitHub Desktop.
creates the 'png' image (The 'Base64.Encoder' class is in Java 1.8)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package rJava; | |
import java.io.File; | |
import java.io.IOException; | |
import java.nio.file.Files; | |
import java.util.Base64; | |
import org.rosuda.JRI.Rengine; | |
public class RSample { | |
public static void main(String[] args) throws IOException { | |
Rengine engine = new Rengine(new String[] { | |
"--no-save" | |
}, false, null); | |
try { | |
int n = 1000; | |
double[] x = new double[n]; | |
for (int i = 0; i < n; i++) { | |
x[i] = 0.0; | |
for (int j = 0; j < 8; j++) | |
x[i] += Math.random(); | |
x[i] = (x[i] - 4.0); | |
} | |
File file = File.createTempFile("plot", ".png"); | |
file.deleteOnExit(); | |
engine.assign("x", x); | |
engine.eval("png('" + file.getAbsolutePath() + "')"); | |
engine.eval("hist(x, xlim=c(-4,4), ylim=c(0,0.6), prob=T, ann=F, panel.first = grid())"); | |
engine.eval("par(new=T)"); | |
engine.eval("plot(density(x), xlim=c(-4,4), ylim=c(0,0.6), xlab='' , ylab='' , main='' , col='red' )"); | |
engine.eval("dev.off()"); | |
byte[] bytes = Files.readAllBytes(file.toPath()); | |
String encode = (Base64.getEncoder()).encodeToString(bytes); | |
String imageSrc = "data:image/png;base64," + encode; | |
String out = "<html><body><img src=\""; | |
out += imageSrc; | |
out += "\"></body></html>"; | |
System.out.println(out); | |
} finally { | |
engine.end(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment