1
votes

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?

1
Maybe you need a virtual x11 device for fonts, see questions about xvfb and/or [r] xvfb. I only ever created base graphs this way.Dirk Eddelbuettel
And, if I may, it is somewhat rude to also hit me with a tweet. I don't owe you support, I do it as long as I have time and while it is no bother. So please don't make it one.Dirk Eddelbuettel
@DirkEddelbuettel: Sorry. I know I'll get your response for sure. So, I did it in the intention that I'll get it quicker. Later I realized that it is not a good act, I should not have done. Wont repeat this in future. Thank you so much for your response. :)Manoj G

1 Answers

5
votes

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