测试之前我更新了所有r包, r和rstudio也是比较新的(半年以内).
我的demo来自 https://cosname.github.io/rmarkdown-guide/rmarkdown-operation.html
首先, 在纯英文情形下, 测试和显示是没有问题的, 如下
---
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
message = FALSE,
warning = FALSE,
dev ='tikz',
fig.align = "center"
)
```
```{r}
# https://cosname.github.io/rmarkdown-guide/rmarkdown-operation.html
par(mar = c(4, 4, 2, .1))
curve(dnorm, -3, 3, xlab = '$x$', ylab = '$\\phi(x)$',
main = 'The density function of $N(0, 1)$')
text(-1, .2, cex = 3, col = 'blue',
'$\\phi(x)=\\frac{1}{\\sqrt{2\\pi}}e^{\\frac{-x^2}{2}}$')
```
若将main改为中文main = '$N(0, 1)$的密度函数'
, 加入设置 fig.showtext = TRUE
, 则latex不能正确显示, 如下
---
output:
pdf_document:
latex_engine: xelatex
header-includes:
- \usepackage{ctex}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
message = FALSE,
warning = FALSE,
dev ='tikz',
fig.align = "center",
fig.showtext = TRUE
)
```
```{r}
# https://cosname.github.io/rmarkdown-guide/rmarkdown-operation.html
par(mar = c(4, 4, 2, .1))
curve(dnorm, -3, 3, xlab = '$x$', ylab = '$\\phi(x)$',
main = '$N(0, 1)$的密度函数')
text(-1, .2, cex = 3, col = 'blue',
'$\\phi(x)=\\frac{1}{\\sqrt{2\\pi}}e^{\\frac{-x^2}{2}}$')
```
当然, 为了和fig.showtext = TRUE
兼容, 可以不用方案dev ='tikz'
, 用其他解决方案如library("latex2exp")
是可以解决问题的, 但感觉上还是dev ='tikz'
生成的图示好看些.