rplotlatticercpprinside

Saving Lattice Plots with RInside and Rcpp


I am trying to build an R application in C++ using RInside. I wanted to save the plots as images in specified directory using codes,

png(filename = "filename", width = 600, height = 400)
xyplot(data ~ year | segment, data = dataset, layout = c(1,3), 
       type = c("l", "p"), ylab = "Y Label", xlab = "X Label",
       main = "Title of the Plot")
dev.off()

It creates a png file in the specified directory if directly run from R. But using C++ calls from RInside, I was not able to reproduce the same result. (I could reproduce all base plots using C++ calls. Problem with only Lattice and ggplots)

I used following codes as well,

myplot <- xyplot(data ~ year | segment, data = dataset, layout = c(1,3), 
                 type = c("l", "p"), ylab = "Y Label", xlab = "X Label",
                 main = "Title of the Plot")
trellis.device(device = "png", filename = "filename")
print(myplot)
dev.off()

png file is getting created if I run the above code in R without any problem. But from C++ calls, a png file with empty panel with title and x-y label is getting created and not a complete plot.

I'm using the function R.parseEval() for C++ call to R.

How to get proper lattice and ggplot2 plots properly?


Solution

  • The following prints a lattice xyplot to a png. It is a minimal example, done as a variation around rinside_sample11.cpp.

    #include <RInside.h>                    // for the embedded R via RInside
    #include <unistd.h>
    
    int main(int argc, char *argv[]) {
    
      // create an embedded R instance
      RInside R(argc, argv);               
    
      // evaluate an R expression with curve() 
      // because RInside defaults to interactive=false we use a file
      std::string cmd = "library(lattice); "
        "tmpf <- tempfile('xyplot', fileext='.png'); "  
        "png(tmpf); "
        "print(xyplot(Girth ~ Height | equal.count(Volume), data=trees)); "
        "dev.off();"
        "tmpf";
      // by running parseEval, we get the last assignment back, here the filename
      std::string tmpfile = R.parseEval(cmd);
    
      std::cout << "Can now use plot in " << tmpfile << std::endl;
    
      exit(0);
    }
    

    It creates this file for me:

    enter image description here