【问题标题】:how to align kable and ggplot in one row (side by side) in r markdown?如何在 r markdown 中将 kable 和 ggplot 在一行(并排)对齐?
【发布时间】:2019-07-14 23:30:39
【问题描述】:

我正在尝试将 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")
}
```

【问题讨论】:

    标签: r ggplot2 latex r-markdown knitr


    【解决方案1】:

    这里可以使用multicollatex 包和两个自定义的latex 命令来避免在编织过程中更改multicol latex 代码:

    ---
    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 下构建的警告足以阻止第一页正确呈现。

    这会产生:

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多