使用knitr和LaTeX在Beamer中设置代码块字体大小

17

我试图让一些R代码适合我的beamer幻灯片。 似乎不可能通过代码块的size参数来更改字体大小,就像你可能为其他knitr类型文档所做的那样。唯一的方法似乎是在每个代码块之前使用\footnotesize。这很令人沮丧,因为我有很多代码块,在许多情况下,我还必须在LaTeX项目符号后使用\normalsize

---
title: "Untitled"
output:
 beamer_presentation:
  includes:
   in_header: header.txt
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, size = "footnotesize")
```

## R Markdown

```{r}
summary(cars)
```

\footnotesize
```{r}
summary(cars)
```

图片描述

在我的header.txt文件中(如下所示),我尝试使用了http://yihui.name/knitr/demo/beamer/上的一些代码,但都没有成功。

\ifdefined\knitrout
\renewenvironment{knitrout}{\begin{footnotesize}}{\end{footnotesize}}
\else
\fi

\makeatletter
\let\oldalltt\alltt
\def\alltt{\@ifnextchar[\alltt@i \alltt@ii}
\def\alltt@i[#1]{\oldalltt[#1]\footnotesize}
\def\alltt@ii{\oldalltt\footnotesize}
\makeatother

... 但实际上我在\def方面很不熟练。

2个回答

7

参考这个tex.SE回答,我们可以重新定义包围R代码的Shaded环境,使其变为footnotesize大小(以及输出时的verbatim环境)。将以下内容添加到您的header.txt文件中:

%% change fontsize of R code
\let\oldShaded\Shaded
\let\endoldShaded\endShaded
\renewenvironment{Shaded}{\footnotesize\oldShaded}{\endoldShaded}

%% change fontsize of output
\let\oldverbatim\verbatim
\let\endoldverbatim\endverbatim
\renewenvironment{verbatim}{\footnotesize\oldverbatim}{\endoldverbatim}

就我所看到的,这只适用于 R 代码(在阴影区域内),而不是 R 输出。有没有办法同时覆盖两者?非常感谢。 - guyabel
@gjabel,我们还需要重新定义“verbatim”,请参见更新的答案。 - scoa
1
非常好,谢谢。我还发现如果我切换 knitr::opts_chunk$set(collapse = TRUE),那么我就不需要担心你的 verbatim 修复(在幻灯片中其他地方使用时有连锁反应),因为 R 输出也在阴影区域中。 - guyabel
在我的情况下似乎不起作用。我得到了:LaTeX Error: Environment Shaded undefined. 有什么想法吗? - Philip Leifeld
这也适用于将Pandoc Markdown中的代码块转换为LaTeX/PDF。 - Ian Turton

1
根据 @Martin Schmelzer 的 output,您可以通过在 rmarkdown 文件中添加以下内容,独立地更改代码字体大小和文本字体大小,并且可以应用于整个文档
def.chunk.hook  <- knitr::knit_hooks$get("chunk")
knitr::knit_hooks$set(chunk = function(x, options) {
  x <- def.chunk.hook(x, options)
  paste0("\n \\", "footnotesize","\n\n", x, "\n\n \\normalsize")
})

从这段代码片段中,你只需要更改"footnotesize""normalsize"参数为你想要的字体大小;第一个参数是代码和输出的字体大小,第二个参数是文本的字体大小。
例如,将代码设置为"tiny",将文本设置为"normalsize":
---
output: beamer_presentation
---

```{r setup, include=FALSE}
def.chunk.hook  <- knitr::knit_hooks$get("chunk")
knitr::knit_hooks$set(chunk = function(x, options) {
  x <- def.chunk.hook(x, options)
  paste0("\n \\", "tiny","\n\n", x, "\n\n \\normalsize")
})
```

# Section 1
```{r}
summary(cars)
```
Text.

# Section 2
```{r}
summary(cars)
```
This works for every chunks.

将其翻译为中文:这是给出的代码: {{link1:Example}}

这在大多数情况下都有效,除非您尝试将代码块用作增量列表的一部分,并且要使用代码块按顺序显示列表元素(在这种情况下,我会使用上面提到的@scoa方法 https://dev59.com/rloT5IYBdhLWcg3wpg1a#38324868)。 - S. Robinson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接