复现步骤
- 安装配置好 Python 环境,最好建立一个虚拟环境,比如用 virtualenv,用环境变量 RETICULATE_PYTHON_ENV 指向该环境
- 安装 bookdown 和 reticulate 包
- 创建一个 bookdown 项目,直接使用自带的那个 demo 项目,插入下面一段文本
```{r}
library(reticulate)
knitr::opts_chunk$set(python.reticulate = TRUE)
reticulate::use_virtualenv(virtualenv = Sys.getenv("RETICULATE_PYTHON_ENV"), required = TRUE)
```
如图 \@ref(fig:reticulate-matplotlib) 所示,在 R Markdown 中执行 Python 绘图代码,并且将图形插入文档。
```{python reticulate-matplotlib,fig.cap="Python 图形",collapse=TRUE}
import numpy as np
import matplotlib.pyplot as plt
plt.switch_backend('agg')
fig = plt.figure()
x = np.arange(10)
y = 2.5 * np.sin(x / 20 * np.pi)
yerr = np.linspace(0.05, 0.2, 10)
plt.errorbar(x, y + 3, yerr=yerr, label='both limits (default)')
plt.errorbar(x, y + 2, yerr=yerr, uplims=True, label='uplims=True')
plt.errorbar(x, y + 1, yerr=yerr, uplims=True, lolims=True,
label='uplims=True, lolims=True')
upperlimits = [True, False] * 5
lowerlimits = [False, True] * 5
plt.errorbar(x, y, yerr=yerr, uplims=upperlimits, lolims=lowerlimits,
label='subsets of uplims and lolims')
plt.legend(loc='lower right')
```
运行输出
仅贴出指向该代码块的报错信息
Error in if (plot2) paste0("\n", d2, "\n</div>") :
missing value where TRUE/FALSE needed
Calls: local ... lapply -> FUN -> hook_plot -> hook_plot_md_base -> paste0
Execution halted
Error in Rscript_render(f, render_args, render_meta) :
Failed to compile dynamic-documents.Rmd
Calls: <Anonymous> ... render_new_session -> tryCatch -> tryCatchList -> Rscript_render
Execution halted
Error: Failed to compile the book to bookdown::gitbook
Execution halted
Makefile:5: recipe for target 'gitbook' failed
make: *** [gitbook] Error 1
注意
保持其他软件版本和环境不动的情况下,都在最新稳定版本下操作,只要将 knitr 从1.26 升级至新版本就会报上述错误
经查
问题可能和此 PR https://github.com/yihui/knitr/pull/1776 有关系,但不十分确定