3

有没有办法用 {xaringan} 演示文稿制作 ggplot 图表?如果我将其导出为 .png 并将其放置为背景图片,我可以做到这一点。但是直接从块输出呢?

4

2 回答 2

4

一个最小的例子在底部。

说明:xaringan的默认 CSS 样式在顶部和底部有 16 像素的填充,在侧面有 64 像素。您可以通过创建 CSS 文件(例如my_css.css包含以下行:

.remark-slide-content.full-slide-fig{
  padding: 0px 0px 0px 0px;
  width: 100%;}

然后在您的 YAML 中引用 CSS 文件。请务必指定滑动比例和fig.asp()块选项相同(例如,16 x 9 用于宽屏输出)。显然,我仍然缺少另一个包含填充的xaringan默认 CSS,因为如果您使用彩色背景,幻灯片顶部仍然会有一小条背景...但是您可以通过将背景颜色设置为白色或透明来避免这种情况out.width="95%"用作块选项。

最后,一定要指定给定的幻灯片使用类full-slide-fig

---
title: "Full-slide figures with **xaringan**"
date: "`r Sys.Date()`"
output: 
  xaringan::moon_reader:
    css: "my_css.css"
    nature:
      ratio: "16:9"
---

class: full-slide-fig

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  fig.asp = 9/16,
  fig.align = 'center',
  echo = F,
  out.width = "95%",
  dpi= 300
)
library(ggplot2)
```

```{r}
ggplot(data = mtcars, mapping = aes(disp, mpg))+
  geom_point()
```

---
于 2021-02-16T18:42:45.487 回答
2

R-markdown本质上只是一种编写markdown文档(如html、pdf等)的方法。本质上,这允许我们使用标准的 markdown、html 和 LaTeX 来解决这些类型的问题。

正如 Yihui 的书rmarkdown-cookbook中所述,我们可以在放置图形时利用这一点。因此,一种方法是简单地保存图像,然后使用标准乳胶命令显示它

```{r image_save, include = FALSE}
library(ggplot2)
p <- ggplot(pressure, aes(x = temperature, y = pressure)) + geom_point()
ggsave('myimage.png', p, dpi = 300) #change dpi for better resolution. 300 is standard
```

\begin{figure}[!p]
  \includegraphics{myimage.png}
  \caption{some latex caption, because someone may prefer this}
  \label{reference_label:1}
\end{figure}

严格来说,这并不能保证情节在它自己的页面上,因为其他图像可能包含在同一页面上。对于更严格的裁决,可以在标头中包含一个文件以包含不同的包或覆盖用于图形放置的基础代码,例如在这个问题的答案中建议。
Yihui 还解释了如何在同一本书的标题中添加代码。

output:
  pdf_document:
    includes:
      in_header: "preamble.tex"

例如,序言可以仅包括

% Contents of preamble.tex
\makeatletter
\@fpsep\textheight
\makeatother

这是链接线程中的第一个建议答案。请注意,如果其中包含一个 latex 包,markdown 编译器可能无法识别这一点,并且 latex 可能需要按照 Yihui 在第 6.11 章中的描述写入一个 Latex 块中。

我确信仅使用可以获得类似的结果,knitr::opts_chunk$set(fig.pos = '!p')但这似乎并没有给出预期的结果。我也确信可以使用 html 做类似的事情,但我不是 html 专家。

最小的可重现示例

---
title: "Untitled"
output: pdf_document
---

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

# Including Plots
Some more text
```{R, include = FALSE}
library(ggplot2)
p <- ggplot(pressure, aes(x = temperature, y = pressure)) + geom_point()
ggsave('myimage.png', p)
```

\begin{figure}[!p]
  \includegraphics{myimage.png}
  \caption{some latex caption, because someone may prefer this}
  \label{reference_label:1} %Label which could be referenced somewhere else in the document.
\end{figure}
text after latex figure
# Random text following the graphis
Here you can place even more information! It is still the same page!
于 2020-08-15T00:25:16.853 回答