Chris
Chris

Reputation: 741

How-to create plots in R using JRI

This is basically the inverse to this question: How to plot a graph using R, Java and JRI? . I want to create a plot in R from a Java program and store it on the harddrive. This is not about displaying an R plot in a java window. I'm using JRE as part of the rJava package. Performing calculations in R from java works just fine.

Executing this in R produces a nice plot:

pdf(file="qqplot.pdf")
x <- rnorm(100)
qqnorm(x); qqline(x)
dev.off()

Nevertheless, executing the same from Java produces the same file, but it is empty. Here's the java code:

private String createNormQQPlot(double[] samples, File filename){

    try{
        // Pass array to R
        engine.assign("samples", samples);
        engine.eval(String.format("pdf(file='%s')",filename.getPath()));
        engine.eval("qqnorm(samples)");
        engine.eval("qqline(samples)");
        engine.eval("dev.off()");
    }catch(Exception e) {
        e.printStackTrace();
        return "";
    }
    return filename.getPath();
}

Any ideas on this are highly appreciated!

Upvotes: 2

Views: 1391

Answers (1)

mitakas
mitakas

Reputation: 11

If you are using some variant of Linux (for example Ubuntu) the solution is to use cairo_pdf instead of pdf:

cairo_pdf(file="qqplot.pdf")
x <- rnorm(100)
qqnorm(x); qqline(x)
dev.off()

There are drawbacks to this approach documented here: R: Cairographics-based SVG, PDF and PostScript Graphics Devices, but at least non-empty pdf files are produced.

Upvotes: 1

Related Questions