我正在尝试将r markdown文件编织为pdf,但无法将ggplot和kable对齐为一行。
我尝试了以下方法:
cat(“ \ twocolumn”)
kable_styling(position =“ float_right”)
下面是一个最小的,可复制的示例
---
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")
}
```
最佳答案
有可能使用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下构建的警告足以阻止第一页正确呈现。
这产生了:
关于r - 如何在r markdown中将kable和ggplot对齐(并排)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57031898/