楚新元 | All in R

Welcome to R Square

简约而不简单的 beamer 幻灯片

楚新元 / 2023-10-01


这篇文章主要参考了黄湘云发表在统计之都上的文章R Markdown 制作 beamer 幻灯片,非常良心的一篇文章,我非常佩服他的耐心和严谨以及精益求精、求真务实的态度。这里分享一个拿来即用的模板,方便后期做 beamer 幻灯片使用。再次感谢湘云。

---
title: "简约而不简单的 beamer 幻灯片"
subtitle: "--- 看看效果"
author: "楚新元"
date: "`r Sys.Date()`"
institute: "家里蹲大学"
documentclass: beamer
output: 
  bookdown::beamer_presentation2:
    toc: FALSE
    number_sections: TRUE
    latex_engine: xelatex
    keep_tex: FALSE
    dev: "cairo_pdf"
    citation_package: natbib  
    theme: Verona
header-includes:
  # - \logo{\includegraphics[height=0.8cm]{`r file.path("path/to/logo.jpg")`}}
  # - \mail{chuxinyuan@outlook.com}  # 邮箱地址
  - \usepackage{pifont}
  - \usepackage{iitem}
  - \setbeamertemplate{itemize item}{\ding{47}}
  - \setbeamertemplate{itemize subitem}{\ding{46}}
  - \usepackage[UTF8,fontset=fandol]{ctex} # 汉化文档
  - \setCJKmainfont{Noto Serif CJK SC}
  - \setCJKsansfont{Noto Sans CJK SC}
  - \setCJKmonofont{Noto Sans Mono CJK SC}
themeoptions: 
  - colorblocks # 彩色的 block
  - blue   # Verona 主题为蓝色风格
  # - showheader  # 展示页面顶部导航
# classoption:
#   - aspectratio = 169
# background-image: "path/to/img"
section-titles: FALSE  # 显示一级标题
toc-title: 目录  # 目录页添加标题
bibliography: "packages.bib"
biblio-title: 参考文献
biblio-style: apalike
natbiboptions: "authoryear,round" # 作者-年份样式,以圆括号包裹
colorlinks: TRUE
link-citations: TRUE
mathspec: TRUE  # mathspec 处理数学公式符号
---

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

```{r}
#| label: "bib"
#| include: FALSE
#| cache: FALSE
# automatically create a bib database for R packages
bib = knitr::write_bib(
  x = c(.packages(), "knitr", "rmarkdown", "bookdown"), 
  file = NULL, prefix = ""
)
bib = unlist(bib)
# remove the ugly single quotes required by CRAN policy
bib = gsub("(\\\n)", " ", bib)
xfun::write_utf8(bib, "packages.bib")
```

## R Markdown 简介

这是一个 R Markdown 演示。Markdown 是一个简单的格式化语法,用于创建 HTML、PDF 和 MS Word 文档。有关使用 R Markdown 的更多详细信息,请参见 <http://rmarkdown.rstudio.com>.

当您单击 **Knit** 按钮时,将生成一个文档,其中既包括内容,也包括文档中任何嵌入 R 代码块的输出。

## Markdown 语法 {#sec-markdown}

轻微强调
:   这是倾斜的文字 _下划线表示强调_, and this is *星花表示强调*.

特别强调
:   这是加粗的文字 **strong emphasis** and __with underscores__.

强烈强调
:   这是斜体加粗的文字 ***三个星花***

删除线
:   This ~~is deleted text.~~

上下标
:   H~2~O is a liquid.  2^10^ is 1024. C^137^ 是一种放射性元素

Table: (\#tab:insert-tab) 表格标题^[注意观察这三列的对其方式。]

| First Header | Second Header | Third Header |
| :----------- | :-----------: | -----------: |
| Cell Left    |  Cell Center  |  Cell Right  |
| Cell Left    |  Cell Center  |  Cell Right  |

## Markdown 列表 {#sec-markdown-list}

### Markdown 无序列表

- 事项 A
- 事项 B

### Markdown 有序列表

1. 事项 1
1. 事项 2

### Markdown 复杂列表

- 事项 A
  1. 子事项 1
  1. 子事项 2
- 事项 B

## R Markdown 嵌入图片  {#sec-rmarkdown-fig}

```{r}
#| label: iris-figure
#| fig.cap: "鸢尾花三个品种花瓣长度概率密度"
#| fig.width: 4
#| fig.height: 3.5
attach(iris)
plot(
  Petal.Length, rep(-0.03, length(Species)), xlim = c(1, 7),
  ylim = c(0, 1.7), xlab = "", ylab = "", pch = 21, cex = 0.7, 
  col = "#00000001", main = "", cex.lab = 0.7, cex.axis = 0.6,
  bg = c("#ff000020", "#00ff0020", "#0000ff20")[unclass(Species)]
)
for (i in 1:3) {
  polygon(
    density(Petal.Length[unclass(Species) == i], bw = 0.2),
    col = c("#ff000040", "#00ff0040", "#0000ff40")[i]
  )
}
```

## R Markdown 嵌入表格  {#sec-rmarkdown-tab}

```{r}
#| label: iris-table
knitr::kable(
  head(iris, 5), 
  caption = "鸢尾花花萼、花瓣长度和宽度特征"
)
```

## R Markdown 嵌入公式  {#sec-rmarkdown-equ}

前两页幻灯片中的图片 \@ref(fig:iris-figure) 和表格 \@ref(tab:iris-table) 是使用 R 语言生成的,下面的公式 \@ref(eq:normal) 是著名的正态分布公式。

\begin{align}
  \mathrm f(x) = \frac{1}{\sigma\sqrt{2\pi}}e^{-\frac{(x-\mu)^2}{2\sigma^2}}
  (\#eq:normal)
\end{align}

## 自定义的块 {#sec-custom-blocks}

::: {.quotation data-latex="[Donald E. Knuth, The \TeX book]"}
Gentle reader: This is a handbook about TEX, a new typesetting
system G intended for the creation of beautiful books—and
especially for books that contain a lot of mathematics.
:::

::: {.exampleblock data-latex="{提示}"}
提示
:::

. . .

::: {.alertblock data-latex="{警告}"}
警告
:::

. . .

::: {.block data-latex="{注意}"}
请读者注意
:::

## 运行环境 {#session-info .allowframebreaks}

制作此幻灯片,我们使用了 bookdown 包 [@bookdown2016]、 rmarkdown 包 [@rmarkdown2018] 和 knitr 包 [@knitr2015],以及  `r R.version.string` 其它软件和环境信息见下方

```{r}
#| comment: ""
#| echo: TRUE
xfun::session_info(
  c("bookdown", "rmarkdown", "knitr"), 
  dependencies = TRUE
)
```

你可以通过如下代码将上面生成的 .pdf 格式的幻灯片转化为 .gif 动画:

library(magick)
img = image_read_pdf("beamer.pdf", density = 300)
img %>% 
  image_resize(geometry_size_pixels(960, 720)) %>% 
  image_animate(delay = 250) %>% 
  image_write("beamer.gif")

另外,这个幻灯片默认是 4:3 的,你可能希望制作 16:9 的幻灯片以适应宽屏,具体设置如下: