Search code examples
pythonrplotlyreticulate

Error when using python-kaleido from R to convert plotly graph to static image


I am trying to use the R reticulate package to convert a plotly graph to a static image. I am using save_image/kaleido.

Link to documentation for save_image / kaleido

Initial setup:

install.packages("reticulate")
reticulate::install_miniconda()
reticulate::conda_install('r-reticulate-test', 'python-kaleido')
reticulate::conda_install('r-reticulate-test', 'plotly', channel = 'plotly')
reticulate::use_miniconda('r-reticulate-test')

Here is my (buggy) attempt:

> library(plotly)
> p <- plot_ly(x = 1:10)
> save_image(p,"test.png")
No trace type specified:
  Based on info supplied, a 'histogram' trace seems appropriate.
  Read more about this trace type -> https://plotly.com/r/reference/#histogram
Error in py_run_string_impl(code, local, convert) : 
  NameError: name 'sys' is not defined
>  

My query is : How do I fix the error that the name 'sys' is not defined?

Funnily, if I do :

> reticulate::repl_python()
Python 3.10.6 (/root/.local/share/r-miniconda/envs/r-reticulate-test/bin/python)
Reticulate 1.26.9000 REPL -- A Python interpreter in R.
Enter 'exit' or 'quit' to exit the REPL and return to R.
>>> import sys
>>> exit
> save_image(p,"test.png")
No trace type specified:
  Based on info supplied, a 'histogram' trace seems appropriate.
  Read more about this trace type -> https://plotly.com/r/reference/#histogram
> 

then it works and produces the picture that I am seeking.

Can someone tell me why I need to invoke repl_python, then import sys and exit it ? How can I fix this ? I need this since I need to create an automated script to create graphs.


Solution

  • As @Salim B pointed out there is a workaround documented to call import sys in Python before executing save_img():

    p <- plot_ly(x = 1:10)
    reticulate::py_run_string("import sys")
    save_image(p, "./pic.png")