Featured image of post 简约而不简单的 beamer 幻灯片

简约而不简单的 beamer 幻灯片

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

# R Markdown 制作 beamer 示例

---
title: "R Markdown 制作 beamer 幻灯片"
subtitle: "--- 看看效果"
author: "楚新元"
institute: "家里蹲大学"
date: "`r Sys.Date()`"
documentclass: beamer
output: 
  bookdown::beamer_presentation2: 
    toc: FALSE
    number_sections: TRUE
    latex_engine: xelatex
    citation_package: natbib
    keep_tex: FALSE
    dev: "cairo_pdf"
    highlight: "default"
    theme: Verona
section-titles: FALSE  # 显示一级标题
toc: FALSE
toc-title: 目录  # 目录页添加标题
bibliography: "packages.bib"
biblio-title: 参考文献
biblio-style: apalike
natbiboptions: "authoryear,round" # 作者-年份样式,以圆括号包裹
colorlinks: TRUE
link-citations: TRUE
mathspec: TRUE  # mathspec 处理数学公式符号
# aspectratio: 169
# background-image: "path/to/img"
themeoptions: 
  - colorblocks # 彩色的 block
  - blue   # Verona 主题为红色风格
  # - showheader  # 展示页面顶部导航
header-includes:
  # - \logo{\includegraphics[height=0.8cm]{`r file.path(R.home("doc"), "html", "Rlogo")`}}
  - \mail{i@cxy.cc}  # 邮箱地址
  - \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}
  # - \usepackage{./beamerthemeVerona}
---

```{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")
```

# 第一部分:介绍 {#intro}

## R 语言 {#sec-intro-r}

::: {.quotation data-latex="[John Gruber]"}
A Markdown-formatted document should be publishable as-is, as plain text, 
without looking like it’s been marked up with tags or formatting instructions.  
:::

Markdown 提供一种简洁的格式语法,用来编辑 HTML、PDF 和 MS Word 文档。
介绍 R Markodwn 文档如何插入图片,更多详情见 <https://rmarkdown.rstudio.com> [@rmarkdown2018]。

R 语言的命名部分来源于最初的两位作者的姓名的首字母 Robert Gentleman 和 Ross Ihaka,
部分是由于贝尔实验室推出的 S 语言 [@base]。

## 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:tbl-example) 表格标题^[注意观察这三列的对齐方式。]

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

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

### Markdown 无序列表

- 事项 A
- 事项 B

### Markdown 有序列表

1. 事项 1
1. 事项 2

### Markdown 复杂列表

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

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

1. Markdown

   1. John Gruber’s Markdown
   1. Pandoc’s Markdown
   1. Hugo's Markdown/Blackfriday’s Markdown 
   1. R Markdown

1. R Markdown

   1. Pandoc
   1. LaTeX
   1. CSS/JS/HTML
   1. Lua

## 睡眠数据 sleep {#sec-fig-sleep}

```{r}
#| label: fig-sleep
#| fig.width: 6
#| fig.height: 3.2
#| fig.cap: "药物对睡眠时长的影响"
#| out.width: "70%"
library(ggplot2)
ggplot(data = sleep, aes(x = group, y = extra, color = group)) +
  geom_boxplot() +
  geom_jitter() +
  theme_minimal(base_family = "DejaVu Sans")
```

## Markdown 插图 {#sec-fig-markdown}

中括号、小括号、大括号分别对应图片标题、路径、属性

```markdown
![...](...){...}
```

![(\#fig:fig-sleep2) 默认图片位置居左^[这里是脚注]](`r knitr::fig_chunk('fig-sleep', 'pdf')`){ width=50%}

## 鸢尾花数据 iris {#sec-fig-iris}

```{r}
#| label: fig-iris
#| 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-tbl-iris}

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

## R Markdown 嵌入公式  {#sec-eq-normal}

前两页幻灯片中的图片 \@ref(fig:fig-sleep) 、 \@ref(fig:fig-iris) 和表格 \@ref(tab:tbl-iris) 是使用 R 语言生成的;图片 \@ref(fig:fig-sleep2) 和表格 \@ref(tab:tbl-example) 是通过 markdown 语法引入的;下面的公式 \@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="{注意}"}
请读者注意
:::

## 运行环境 {#sec-sessionInfo .allowframebreaks}

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

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

# 第二部分:其他 {#else}

## 设置主题 {#sec-install-verona}

Ivan Valbusa 开发了 [Verona 主题的 Beamer 模版](https://bitbucket.org/rivanvx/beamer),
目前 CTAN 上的版本是 0.2,文档说明见 <https://www.ctan.org/pkg/beamer-verona>
这个主题的宏包依赖很少!我很喜欢!

```r
tinytex::tlmgr_install('beamer-verona')
```

# beamer 幻灯片效果

你可以通过如下代码将上面生成的 .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")

# 您需要的是 16:9 的效果?

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

  • beamerthemeVerona.sty 文件放在工程目录下,将里面的 12.8cm 和 12.69cm 都调整成 15.9cm。
  • yaml 的 header-includes 下面增加一行代码:\usepackage{./beamerthemeVerona}
  • yaml 的 classoption 下面增加一行代码:aspectratio = 169