2015年1月11日日曜日

math/RでPlotをrJava経由でやってみる(SVG)

rJavaを用いてJavaからRを動かしたPostのRSampleと入れ替えてみる.
package rJava;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
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", ".svg");
file.deleteOnExit();
engine.assign("x", x);
engine.eval("svg('" + 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 content = new String(bytes, StandardCharsets.UTF_8);
content = content.substring(content.indexOf('\n'));
String out = "<html><body>\n";
out += content;
out += "\n</body></html>";
System.out.println(out);
} finally {
engine.end();
}
}
}
view raw RSample.java hosted with ❤ by GitHub


結果

<html><body>

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="504pt" height="504pt" viewBox="0 0 504 504" version="1.1">
<defs>
<g>
<symbol overflow="visible" id="glyph0-0">
<path style="stroke:none;" d="M 0.390625 0 L 0.390625 -8.609375 L 7.21875 -8.609375 L 7.21875 0 Z M 6.140625 -1.078125 L 6.140625 -7.53125 L 1.46875 -7.53125 L 1.46875 -1.078125 Z M 6.140625 -1.078125 "/>
</symbol>
…
<path style="fill:none;stroke-width:0.075;stroke-linecap:round;stroke-linejoin:round;stroke:rgb(74.509804%,74.509804%,74.509804%);stroke-opacity:1;stroke-miterlimit:10;" d="M 59.039062 416.800781 L 473.761719 416.800781 "/>
</g>
</g>
</svg>

</body></html>


参考

0 件のコメント: