我正在尝试将r markdown文件编织为 pdf ,但是我无法将ggplot和kable对齐成一行。
我尝试了以下方法:
下面是一个最小的,可复制的示例
---
title: "Untitled"
output: pdf_document
classoption: landscape
---
\newpage
```{r cars, echo=FALSE, fig.width=3, fig.height=3, results="asis", message=FALSE}
library(dplyr)
library(knitr)
library(kableExtra)
library(ggplot2)
dt <- split(mtcars, f = mtcars[, "cyl"]) %>% lapply(., function(x) x[1:5, 1:4])
for (i in seq_along(dt)) {
print(
kable(dt[[i]]) %>% kable_styling("striped") %>% add_header_above(c(" " = 1, "Group 1" = 2, "Group 2" = 2))
)
print(
ggplot(data = dt[[i]], aes(x = mpg, y = cyl, group = 1)) +
geom_line(aes(y = disp), linetype = "solid", colour = "#000000")
)
cat("\\pagebreak")
}
```
答案 0 :(得分:3)
这里有可能使用multicol
乳胶软件包和两个自定义乳胶命令来避免在编织过程中更改multicol乳胶代码:
---
title: "Untitled"
header-includes:
- \usepackage{multicol}
- \newcommand{\btwocol}{\begin{multicols}{2}}
- \newcommand{\etwocol}{\end{multicols}}
output: pdf_document
classoption: landscape
---
\newpage
\btwocol
```{r cars, echo=FALSE, fig.width=3, fig.height=3, results="asis", message=FALSE}
library(dplyr)
library(knitr)
suppressWarnings(library(kableExtra))
library(ggplot2)
dt <- split(mtcars, f = mtcars[, "cyl"]) %>%
lapply(., function(x) x[1:5, 1:4])
for (i in seq_along(dt)) {
print(
kable(dt[[i]]) %>%
kable_styling("striped") %>%
add_header_above(c(" " = 1,
"Group 1" = 2,
"Group 2" = 2))
)
cat("\\columnbreak")
print(
ggplot(data = dt[[i]], aes(x = mpg, y = cyl, group = 1)) +
geom_line(aes(y = disp), linetype = "solid", colour = "#000000")
)
cat("\\pagebreak")
}
```
\etwocol
请注意,我必须禁止来自kableExtra的警告,因为有关在我使用R v3.6.0时在R v3.6.1下构建的警告足以阻止第一页正确呈现。
这会产生: