在 R 中使用 reticulate 导入 matplotlib
回答问题
我刚开始在 R 中使用 reticulate 包,但我仍然发现了一些问题。特别是,导入 matplotlib 并不顺利。我尝试了两种不同的方法,每种方法都有不同的错误消息。
首先,在 RStudio 交互式 shell 中使用 repl\python:
library(reticulate)
use_python('/home/craig/anaconda3/bin/python')
py_discover_config()
repl_python()
import matplotlib.pyplot as plt
打开的 REPL Python shell 似乎具有正确的版本和所有内容,但是当我尝试导入 matplotlib.pyplot 时,我看到以下内容:
ImportError: /lib/x86_64-linux-gnu/libz.so.1: version `ZLIB_1.2.9' not found (需要 /home/craig/anaconda3/lib/python3.6/site-packages/ matplotlib/../../.././libpng16.so.16)
安装 zlib(使用sudo apt-get install lib64z1-dev lib64z1)似乎没有改变任何东西。 FWIW,import matplotlib工作得很好,只要我不需要pyplot。
我也尝试在 R Markdown 文档中做同样的事情:
```{r}
library(reticulate)
py_discover_config()
import matplotlib.pyplot as plt
This time I saw:
Error in py\_get\_attr\_impl(x, name, silent): AtributeError: module 'matplotlib' has no attribute 'pyplot' Calls: ... $.python.builtin.object -> py\_get\_attr -> py\_get\_attr\_impl -> .Call Execution halted
Any ideas what might be going on here?
Thanks!
**UPDATE:** As I mentioned in the comments, installing the developer version of reticulate fixes some of the problems, but not all. If I try to run this Rmd:
library(reticulate)
use_python('/home/craig/anaconda3/bin/python')
import matplotlib.pyplot as plt
I get the following error messages:
py_run_string_impl(代码,本地,转换)中的错误: ImportError:/home/craig/anaconda3/lib/python3.6/site-packages/PyQt5/../../../libxcb-dri3.so.0:未定义符号:xcb_send_request_with_fds
详细追溯: <module> 中的文件“<string>”,第 1 行 <module> 中的文件“/home/craig/anaconda3/lib/python3.6/site-packages/matplotlib/pyplot.py”,第 116 行 _backend_mod,new_figure_manager,draw_if_interactive,_show u003d pylab_setup() pylab_setup 中的文件“/home/craig/anaconda3/lib/python3.6/site-packages/matplotlib/backends/init.py”,第 60 行 [后端名称],0) <module> 中的文件“/home/craig/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_qt5agg.py”,第 16 行 从 .backend_qt5 导入( <module> 中的文件“/home/craig/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_qt5.py”,第 18 行 导入 matplotlib.backends.qt_editor.figureoptions 作为 figureoptions <module> 中的文件“/home/craig/anaconda3/lib/python3.6/site-packages/matplotlib/backends/qt_editor/figureoptions.py”,第 20 行 调用:<匿名> ... force -> py_run_string -> py_run_string_impl -> .Call 执行停止
When I tried googling the error text, a [similar error with xcb](https://github.com/ValveSoftware/steam-for-linux/issues/5249) does seem to be coming up in a context that is, as far as I can tell, not so relevant.
## Answers
I was able to get things working by changing the R Markdown code block to read:
library(reticulate)
use_python('/usr/bin/python3')
import matplotlib.pyplot as plt
I still don't really understand why, but it seems that `reticulate` doesn't play nice with anaconda installations. Maybe it has something to do with anaconda being set up to work well with an interactive Jupyter notebook.
更多推荐

所有评论(0)