knitr生成PDF时如何实现章节标题与横向排版图片同页显示
问题场景
knitr生成PDF文档时,需要把章节标题和横向排版的图片放在同一个页面。
常见错误写法及问题
写法1:标题放在landscape环境外
--- title: "Untitled" output: pdf_document date: '2022-06-21' header-includes: - \usepackage{pdflscape} --- # Section title \begin{landscape} ```{r pressure, out.extra= 'angle=0', echo = F} plot(pressure)
\end{landscape}
问题:`pdflscape`包的`\begin{landscape}`命令会自动触发分页,最终章节标题留在上一页,横向图片单独占下一页。 ### 写法2:markdown格式标题放在landscape环境内 不管标题前后加不加空行,只要在landscape环境里直接用`#`写markdown标题: ```r --- title: "Untitled" output: pdf_document date: '2022-06-21' header-includes: - \usepackage{pdflscape} --- \begin{landscape} # Section title ```{r pressure, echo=FALSE} plot(pressure)
\end{landscape}
编译时会直接抛出错误:
! You can't use `macro parameter character #' in vertical mode.
l.74 #
Section title
Error: LaTeX failed to compile sectionTitle.tex. See sectionTitle.log for more info.
Execution halted
原因是knitr在解析LaTeX环境内部内容时,无法正确识别markdown格式的`#`标题语法,会把`#`当做LaTeX的特殊字符处理触发报错。 --- # 可行解决方案 在landscape环境内部直接使用LaTeX原生的章节命令定义标题,同时微调顶部边距、控制图片宽度,保证标题和图片能放在同一横向页面内,完整可运行代码如下: ```r --- title: "Untitled" output: pdf_document date: '2022-06-21' header-includes: - \usepackage{pdflscape} --- \begin{landscape} % 微调顶部边距,避免标题位置过靠下 \vspace*{-1.5em} % 一级标题对应\section,二级用\subsection,三级用\subsubsection \section{Section title} ```{r pressure, echo=FALSE, out.width="85%", fig.align="center"} plot(pressure)
\end{landscape}
- 不同层级的markdown标题对应不同的LaTeX命令:`# 标题`对应`\section{标题}`,`## 标题`对应`\subsection{标题}`,`### 标题`对应`\subsubsection{标题}` - `\vspace*{-1.5em}`的数值可以根据实际排版效果调整,作用是压缩landscape环境默认的顶部留白 - 图片的`out.width`参数建议设置为页面宽度的80%-90%,避免图片尺寸过大被挤到下一页 - *注意:不要在LaTeX章节命令前后添加多余空行,否则可能触发knitr的块解析异常* --- 内容的提问来源于stack exchange,提问作者raphael_ldl
相关产品推荐
相关产品推荐

