簡體   English   中英

Rmarkdown Latex 對齊一個圖和一個kbl表(輸出PDF)

[英]Rmarkdown Latex Align a figure and a kbl table (output PDF)

我有以下 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

在此處輸入圖像描述

筆記:

  1. 從概念上講,解決方案在此處接受的答案中提出; 但是,我無法在那里重現代碼。

  2. 我剝離了您的初始代碼以留下一個最小的示例。 也就是說,我刪除了 table t2的代碼以及library(knitr)library(xtable)的調用。

  3. 對初始代碼的其他更改包括:

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

    • 添加了一些 lorem ipsum 文本以更清楚地查看對象是如何相互對齊的

    • 在生成表格的 R 代碼塊和 plot 中設置results="asis"

    • 使用 function kable()代替kbl() 如果您使用kbl() ,則該表相對於 plot 有點偏離(我不知道為什么)。 我建議您同時使用這兩個功能

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM