如何在r markdown中将kable和ggplot对齐(并排)? [英] how to align kable and ggplot in one row (side by side) in r markdown?

查看:279
本文介绍了如何在r markdown中将kable和ggplot对齐(并排)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将r markdown文件编织为 pdf ,但是我无法将ggplot和kable对齐成一行.

I am trying to knit an r markdown file to pdf, but I can't align ggplot and kable in one row.

我尝试了以下方法:

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

推荐答案

这里有可能使用multicol乳胶包和两个自定义乳胶命令来规避在编织过程中更改multicol乳胶代码:

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

请注意,我必须禁止来自kableExtra的警告,因为当我使用R v3.6.0时,有关在R v3.6.1下构建的警告足以阻止第一页正确呈现.

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.

这会产生:

这篇关于如何在r markdown中将kable和ggplot对齐(并排)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆