I am trying to knit an r markdown file to pdf, but I can't align ggplot and kable in one row.
I have tried following ways:
- cat("\twocolumn")
- kable_styling(position = "float_right")
Below is a minimal, reproducible example
---
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")
}
```
Here is a possibility using the multicol
latex package and two custom latex commands to circumvent the multicol latex code from being changed during the knit process:
---
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
Note that I had to suppress warnings from kableExtra because the warning about being built under R v3.6.1 when I am using R v3.6.0 was enough to prevent the first page from rendering correctly.
And this produces: