Rmarkdown Latex 对齐图形和 kbl 表(输出 PDF)

标签 r ggplot2 latex r-markdown

我有以下 Rmarkdown 试用版:

---
title: "Test kableExtra"
date: "3/20/2021"
output: pdf_document
classoption: landscape
---

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

```

# R Markdown

```{r echo=FALSE}
library(knitr)
library(xtable)

dt <- mtcars[1:5, 1:6]

t1 <- kbl(dt, booktabs = T)
t2 <- kbl(dt, booktabs = T)

t3 <- ggplot(dt,aes(x=mpg,y=cyl)) +
  geom_point()

png(file="plot1.png",width=200,height=200)
print(t3)
dev.off() # close the png file

```
Some Text

\begin{table}[!h]
    \begin{minipage}{.5\linewidth}
      \centering
```{r echo=FALSE}
t1
```
\end{minipage}%
    \begin{minipage}{.5\linewidth}
      \centering
    \includegraphics[width=\textwidth]{plot1.png}
    \end{minipage}
\end{table}

output

当你编织它时它工作正常,但我希望图表和表格在顶部对齐。 有人有想法吗?

如果您有更好的主意,将 ggplot 放在 kbl 表旁边,我洗耳恭听!

谢谢, 迈克尔

最佳答案

以下代码可能会有所帮助:

---
title: "Test kableExtra"
date: "3/20/2021"
output: pdf_document
header-includes:
  - \usepackage{multicol}
  - \newcommand{\btwocol}{\begin{multicols}{2}}
  - \newcommand{\etwocol}{\end{multicols}}
classoption: landscape
---

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

# R Markdown

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis 
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore 
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.

\btwocol

```{r echo=FALSE, results="asis", message=FALSE}
# sample data
dt <- mtcars[1:5, 1:6]

# create the table
t1 <- kable(dt, booktabs = TRUE)

# create the plot
t3 <- ggplot(dt,aes(x=mpg, y=cyl)) +
  geom_point()

# print the table 
print(t1)

cat("\\columnbreak")

# print the plot
print(t3)

cat("\\pagebreak")
```

\etwocol

enter image description here

注意事项:

  1. 概念上,解决方案在已接受的答案中提出 here ;但是,我无法在那里重现代码。

  2. 我精简了您的初始代码以留下一个最小示例。也就是说,我删除了表 t2 的代码以及对 library(knitr)library(xtable) 的调用。

  3. 对初始代码的其他更改包括:

    • 在 Rmd 文件的 YAML 部分的 header-includes 下调用 LaTeX 包和命令

    • 添加一些 lorem ipsum 文本以更清楚地查看对象如何相对于彼此对齐

    • 在生成表格和绘图的 R 代码块中设置 results="asis"

    • 使用函数 kable() 代替 kbl()。如果您使用 kbl(),则该表相对于情节有点偏离(我不知道为什么)。我建议你同时使用这两个函数

关于Rmarkdown Latex 对齐图形和 kbl 表(输出 PDF),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66726204/

相关文章:

r - 将逻辑回归与条形图结合起来以获得成熟度结果

python - 相当于 Pandas 数据框中 R 的 'rep'

r - 晶格中多个 y 变量的条件面板函数

r - 当范围每天都在变化时,如何使用 plot() 调整 x 轴?

r - 避免在 ggplot2 中使用 geom_point 进行绘图叠加

r - ggplot,x轴上带有字符串

java - 在 Java 中生成 LaTeX 输出

latex - 评估一个函数并分配给一个常量以用作 Tikz/pgfplots 中的刻度标记

通过存储在列表 R 中的多个数据帧运行条件

pdf - 使用 Maven 维护用户文档