美文网首页数据科学与R语言数据-R语言-图表-决策-Linux-PythonR
R语言学习笔记--R bookdown图表设置中英文双标题

R语言学习笔记--R bookdown图表设置中英文双标题

作者: 逍遥尐生 | 来源:发表于2019-04-01 12:47 被阅读95次

一. 测试文档,该文档修改自 bookdown 的官方中文模板

该方案可以实现同时生成pdf和html两种格式的文件,pdf文件中实现双标题,html文件可正常生成单个标题。

二. 结合 CTEX 配置使用 latex 的运行环境

首先安装 TeX 用的发行版,yihui等推荐使用 TinyTex

配置template.tex文件:template.tex文件位于 latex 文件夹中,在\begin{document}前加入:

\usepackage{ctex}
\usepackage{bicaption}
\captionsetup[figure][bi-first]{name=图}
\captionsetup[figure][bi-second]{name=Figure}
\captionsetup[table][bi-first]{name=表}
\captionsetup[table][bi-second]{name=Table}

三. 配置index.rmd文件

ps: 为了显示的需要 ``` 符号用 ---代替;
ps: 如果采取图片双标题方案二,则跳过这一步。

需要对knitr包的hooks进行一定的修改,在index.Rmd文件中加入:

---{r setup_knitrfigure, include = FALSE}
    library(knitr) 
      if(is_latex_output()){
        knit_hooks$set(plot = function(x, options) {
          if(!is.null(options$bicap)){
            options$fig.cap = NULL
            paste("\\begin{figure}[!htp]",
                  hook_plot_tex(x, options), 
                  "\\bicaption{", options$bicap[1], "}{",options$bicap[2],"}", 
                  "\\end{figure}", sep = "")
          }  else{
            hook_plot_tex(x, options)
          }
        })
      } 
---

四. 在01-introduction.rmd文件中演示相应设置

4.1 图片双标题
生成图片
---{r}
  dir.create('images')
  png('images/fig.png')
  plot(cars, main = 'png')
  dev.off()
  pdf('images/fig.pdf')
  plot(cars, main = 'pdf')
  dev.off()
---
插入图片

方案一:

---{r fig1, out.width='50%', bicap=c('中文题目','English caption'), fig.cap="中文题目", fig.align="center"}
  knitr::include_graphics("images/fig.png")
---

images文件夹中同时存在fig.pdf文件,生成pdf文档时,knitr会自动调用fig.pdf文件,如此生成高质量的pdf文件

(ref:fig2) 试试**复杂格式**的中文题目`cars` 

---{r fig2, out.width='50%',fig.cap='(ref:fig2)', bicap = c('(ref:fig2)',"English caption2"), , fig.align="center"}
knitr::include_graphics("images/fig.png") 
---

方案二:

\begin{figure}
---{r, out.width='50%', fig.align="center", echo = FALSE}
  knitr::include_graphics("images/fig.png")
---
\bicaption{在不同调谐因子\textit{k}下的缺损文件可比较性实验结果}{Incompletele comparable probability in different factor k}
\label{fig:fig3}
\end{figure}
---{r fig3, echo = FALSE, out.width='50%', fig.align="center", fig.cap="在不同调谐因子k下的缺损文件可比较性实验结果"}
  library(knitr)
  if(is_html_output()) include_graphics("images/fig.png")
---
4.2 表格双标题
\begin{table}[!htbp]
    \centering
    \bicaption{表中文题目}{Table English caption}
    \label{tab:Tab1}
---{r, echo = FALSE}
  knitr::kable( head(iris), booktabs = TRUE)
---
\end{table}

---{r Tab1, echo = FALSE}
  library(knitr)
  if(is_html_output()) knitr::kable(head(iris), caption = "表中文题目", booktabs = TRUE)
---

大功告成。

主要参考:Latex图表设置中英文双标题(非ccaption宏包)How to use bicaption instead of caption?,感谢dapengde等的指点

相关文章

网友评论

    本文标题:R语言学习笔记--R bookdown图表设置中英文双标题

    本文链接:https://www.haomeiwen.com/subject/ywtvbqtx.html