Rmarkdown 中同一行的 Kableextra 表和 ggplot 图(PDF - 不是 Flexdashboard)

2024-04-27

我一直在尝试使用 R Markdown 创建一些 PDF 报告。我很难正确布局。基本上,我需要在同一行上有一个 KableExtra 创建的表(数据框)和一个 ggplot 图。我探索了一些网格包,但无法让它工作。

这是我的代码:

---
title: "Untitled"
author: ""
date: "14 June 2018"
output: pdf_document

---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
library(reshape2)
library(dplyr)
library(kableExtra)
```

## R Markdown

```{r chart, echo=FALSE}
Years <-  c("2016","2016","2016","2016",
           "2017","2017","2017","2017")
Quarters <-  c("Q1","Q2","Q3","Q4",
        "Q1","Q2","Q3","Q4")
Series1 <- c("100","200","300","400","500","600","700","800")
Series1 <- as.numeric(Series1)

df <- data.frame(Years,Quarters, Series1)

library(ggplot2)
ggplot(df) +
        geom_point(aes(x = Quarters, y = Series1)) + 
        facet_wrap( ~ Years, strip.position = "bottom",scales = "free_x") + 
        theme(panel.spacing = unit(0,"lines"), strip.background = 
element_blank(),
              strip.placement = "outside")
```
```{r table, echo=FALSE}

Table <- dcast(df, Years ~ Quarters, fun.aggregate = sum, value.var = 
"Series1")


Table <- Table %>%
        kable(format = "latex", caption = "Balances", booktabs = TRUE) %>%
        kable_styling(latex_options = c("striped","hold_position","condensed"),
                      font_size = 10) 
Table
```

如果你不强烈依赖kable()我可以提供这个gridExtra解决方案。使用时tableGrob(kable(.))乳胶代码不会以某种方式执行,也许其他人想出了如何在 a 中执行乳胶代码tableGrob().

```{r chart, echo=FALSE, message=FALSE}
df <- data.frame(Years=rep(2016:2017, each=4),
                 Quarters=rep(paste0("Q", 1:4), 2),
                 Series1=seq(100, 800, 100))

library(ggplot2)
p1 <- ggplot(df) +
  geom_point(aes(x=Quarters, y=Series1)) + 
  facet_wrap( ~ Years, strip.position="bottom", scales="free_x") + 
  theme(panel.spacing=unit(0, "lines"), 
        strip.background=element_blank(), 
        strip.placement="outside", 
        aspect.ratio=1)  # set aspect ratio

Table <- dcast(df, Years ~ Quarters, fun.aggregate=sum, value.var="Series1")

library(gridExtra)
t1 <- tableGrob(Table, theme=ttheme_minimal(), rows=NULL)  # transform into a tableGrob

grid.arrange(p1, t1, nrow=1)
```

Produces: output

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rmarkdown 中同一行的 Kableextra 表和 ggplot 图(PDF - 不是 Flexdashboard) 的相关文章

随机推荐