使用 R 中的 python-kaleido 将绘图图转换为静态图像时出错

use*_*823 5 python r plotly reticulate

我正在尝试使用 R 网状包将绘图转换为静态图像。我正在使用 save_image/kaleido。

save_image / kaleido 文档的链接

初始设置:

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')
Run Code Online (Sandbox Code Playgroud)

这是我的(有缺陷的)尝试:

> 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
>  
Run Code Online (Sandbox Code Playgroud)

我的查询是:如何修复名称“sys”未定义的错误?

有趣的是,如果我这样做:

> 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
> 
Run Code Online (Sandbox Code Playgroud)

然后它就会工作并产生我正在寻找的图片。

有人可以告诉我为什么我需要调用 repl_python,然后导入 sys 并退出它?我怎样才能解决这个问题 ?我需要这个,因为我需要创建一个自动脚本来创建图表。

Tap*_*per 12

正如 @Salim B 指出的,有一个解决方法记录import sys在执行之前在 Python 中调用save_img()

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