how to align kable and ggplot in one row (side by side) in r markdown?

自古美人都是妖i 提交于 2019-12-10 10:30:01

问题


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")
}
```

回答1:


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:



来源:https://stackoverflow.com/questions/57031898/how-to-align-kable-and-ggplot-in-one-row-side-by-side-in-r-markdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!