ลองดูตัวอย่างที่ผมเขียนนี้ครับ ไอเดียก็คือว่าให้มันเขียนภาพเป็นไฟล์ pdf ด้วยคำสั่ง ggsave แล้วเรียกกลับมาใน Mathematica ด้วย Import โค้ดที่เขียนนี้ดัดแปลงมาจาก https://mathematica.stackexchange.com/questions/16726/how-to-get-a-plot-generated-by-r-returned-in-an-output-cell
(* using R that already installed on the computer *)
R363 = "C:\\Data-Work\\Programs\\R-3.6.3\\App\\R-Portable";
InstallR["RHomeLocation" -> R363, "RVersion" -> "3.6.3",
"NativeLibLocation" ->
"C:\\Data-Work\\Programs\\R-3.6.3\\App\\R-Portable\\library\\rJava\\\
jri\\x64"]
REvaluate["
library(ggplot2)
"]
(* export ggplot as pdf file *)
Wrapper = RFunction["function(filename,plotfun){
ggsave(filename, plot=plotfun(), width=6, height=4, \
device=cairo_pdf)
}"];
(* generate the plot as pdf and import back to show in Mathematica *)
Getggplot[plotFun_] := Module[{tempfile, rcode, runcode},
tempfile = FileNameJoin[{$TemporaryDirectory, "temp.pdf"}];
If[FileExistsQ[tempfile], Quiet@DeleteFile[tempfile]];
rcode = "ADA <- ggplotcmd;";
runcode = StringReplace[rcode, {"ggplotcmd" -> plotFun}];
Wrapper[tempfile, RFunction["function()" <> "{" <> runcode <> "}"]];
If[! FileExistsQ[tempfile], Return[$Failed]];
Import[tempfile] // First
];