I am running R scripts inside a Python framework using the rpy2
package. I am running a function within an R script, which returns a ggplot
as part of a larger collection. In Python, the class of this collection is either a rpy2.robjects.vectors.ListVector
or an rpy2.rlike.container.OrdDict
. (It is the former type in the toy example below).
Given this output of a ggplot in rpy2, how can I visualize the object? Other questions and examples I have seen deal with constructing the ggplot in rpy2; however, what I want to do is to work in rpy2 to visualize the ggplot that is output from an existing R script.
R script (ggtoy.R
):
library(ggplot2)
data(Loblolly)
funfunfunction <- function(title="hello world!") {
p <- ggplot(Loblolly, aes(x=height, y=age)) + geom_point()
p <- p + ggtitle(title)
l <- list("title"=title,"random"="something else")
return(list("ggdict"=p,"sublist"=l))
}
Python:
import rpy2.robjects as ro
from rpy2.robjects.lib import ggplot2
r_script_name = 'ggtoy.R'
r_fn_name = 'funfunfunction'
params = { "title" : "new title!" }
ro.r(f"source('{r_script_name}', chdir = TRUE)")
r_fn = ro.globalenv[r_fn_name]
r_fn_output = r_fn(**params)
# stuck here
ggplot2.ggplot(r_fn_output[0])
I am unsure what to do with r_fn_output[0]
to be able to engage with the ggplot
image, either for visualization or download. It seems like there should be some easy way to do this in the high-level rpy2 API.
At the very end of the rpy2.robjects.lib.ggplot2
script there is a convenient function ggplot2_conversion()
, which is not documented elsewhere as far as I can find. Simply running this function on my ggplot/gg object worked great. It can then be visualized in iPython using rpy2.ipython.ggplot.image_png()
.
import rpy2.robjects as ro
from rpy2.robjects.lib import ggplot2
from rpy2.ipython.ggplot import image_png
r_script_name = 'ggtoy.R'
r_fn_name = 'funfunfunction'
params = { "title" : "new title!" }
ro.r(f"source('{r_script_name}', chdir = TRUE)")
r_fn = ro.globalenv[r_fn_name]
r_fn_output = r_fn(**params)
converted = ggplot2.ggplot2_conversion(r_fn_output[0])
image_png(converted)