How to write complex kable and ggplot in sections (row and column alignment) to pdf using R Markdown?

邮差的信 提交于 2019-12-13 03:22:38

问题


I am trying to knit several kable and ggplot in sections in one page, details are in the minimal and reproducible example below.

I have tried

  • cat("\\twocolumn")
  • kable_styling(position = "float_right")
  • \usepackage{multicol} (Previous Question)

Below is the code

---
title: "Untitled"
output: pdf_document
classoption: landscape
---

\newpage

```{r cars, echo=FALSE, results="asis", fig.width=3, fig.height=2, 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(cbind(dt[[i]], dt[[i]], dt[[i]], dt[[i]], dt[[i]])) %>% 
      kable_styling("striped")
  )


  print(
    ggplot(data = dt[[i]], aes(x = mpg, y = cyl, group = 1)) + 
      geom_line(aes(y = disp), linetype = "solid", colour = "#000000")
  )


  print(
    ggplot(data = dt[[i]], aes(x = mpg, y = cyl, group = 1)) + 
      geom_line(aes(y = disp), linetype = "solid", colour = "#000000")
  )

  print(
    kable(dt[[i]]) %>% 
      kable_styling("striped") %>% 
      add_header_above(c(" " = 1, 
                         "Group 1" = 2, 
                         "Group 2" = 2))
  )

  cat("\\twocolumn")

  print(
    kable(dt[[i]]) %>% 
      kable_styling("striped") %>% 
      add_header_above(c(" " = 1, 
                         "Group 1" = 2, 
                         "Group 2" = 2))
  )

  cat("\\pagebreak")


  print(
    ggplot(data = dt[[i]], aes(x = mpg, y = cyl, group = 1)) + 
      geom_line(aes(y = disp), linetype = "solid", colour = "#000000")
  )
  cat("\\onecolumn")

  cat("\\pagebreak")
}
```

I want the final result to be:

  • each page, except the title page, contains
    • 1st row: kable
    • 2nd row: ggplot, ggplot, kable
    • 3rd row: kable, ggplot
  • section property
    • adjustable row height
    • adjustable column width

来源:https://stackoverflow.com/questions/57294988/how-to-write-complex-kable-and-ggplot-in-sections-row-and-column-alignment-to

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