Search code examples
c#rr.net

How to save a plot generated via R.NET to a file on disk?


I am using R.NET to generate plots (using ggplot) and I want to save these graphs in PNG format on disk. Whenever I call engine.Evaluate("ggsave('C:\path\to\file.png', myPlot)") the program abruptly aborts with exit code 2 without anything being written to disk; no error is displayed when this happens. It is also not possible to write the plot to a file using png() or pdf(). This problem is not specific to ggplot, however - I also cannot store plots generated via the native plot function.

I could narrow down the problem to the line containing either ggsave() or png()/pdf(): when this line is executed, the program aborts. Since I can actually see the plots generated by both, ggplot() and plot(), the plotting itself does not seem to be the issue.

You should be able to recreate what I described using the following C# code:

using RDotNet;

namespace Test {
  class Program {
    static void Main(string[] args) {
      REngine.SetEnvironmentVariables();
      REngine engine = REngine.GetInstance();

      engine.Evaluate("png('D:\\Test.png')");
      engine.Evaluate("plot(rnorm(1000))");
      engine.Evaluate("dev.off()");  
    }
  }
}

Apparently, this code should work without any issues.

When running

png('D:\\Test.png')
plot(rnorm(1000))
dev.off()

in R, a plot is generated and saved to Test.png successfully.

I am using .NET Framework 4.6.1, R.NET 1.7.0, and R 3.4.2. R is not installed on my computer and registry entries have not been created for R - I am just using the R DLLs as described here.


Solution

  • It's not that you cannot have backslashes as you mention in your answer. Although forward slashes solve your problem as well, I think it might help in the future if I explain the other solution.

    You have to escape your backslash twice.

    Once for C#, once for R.

    Calling Evaluate like this

    engine.Evaluate("png('D:\\Test.png')");
    

    will call the R engine with the string: "png('D:\\Test.png')", which, if you evaluate it is just: png('D:\Test.png'). If you typed that into R you'd get an error as well.

    If you want to run the R command png('D:\\Test.png'), you have to escape that string, which has two backslashes after escaping both it becomes: "png('D:\\\\Test.png')".