Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 991
user2338823 Avatar asked Jul 17 '26 05:07

user2338823


2 Answers

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")
like image 153
Tapper Avatar answered Jul 19 '26 18:07

Tapper


I tried the reticulate option. It took a long time, and it was difficult to ensure the compatibility of the different software to be used in the Conda environment. In the end, it still wasn't functioning. So, I gave up on reticulate and saved my Plotly graph as an HTML file, then exported it as a PDF. It's not very elegant, but it's efficient. It also works to export as a PNG or JPEG.

htmlwidgets::saveWidget(my_interactive_plot,
            "./html/my_plot.html", 
            selfcontained = TRUE)
pagedown::chrome_print("./html/my_plot.html", 
                       output = "./my_plot.pdf")
like image 31
Arnaud P. Avatar answered Jul 19 '26 17:07

Arnaud P.