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

时间:2018-06-14 13:09:33

标签: r ggplot2 latex pandoc kable

我一直在尝试使用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
```

1 个答案:

答案 0 :(得分:1)

如果您不强烈依赖kable()我可以提供此gridExtra解决方案。当使用tableGrob(kable(.))时,乳胶代码将不会以某种方式执行,也许其他人想出如何在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)
```

<强> 产地: output