A Kableextra table and a ggplot plot on same row i

2019-08-14 17:59发布

问题:

I have been experimenting with R Markdown to create some PDF reports. I am having difficulty in getting the layout right. Basically, I need to have a KableExtra created table (dataframe) and a ggplot plot on the same row. I have explored some grid packages, but couldn't get it to work.

Here is my code:

---
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:

If you are not strongly depending on kable() I can provide this gridExtra solution. When using tableGrob(kable(.)) the latex code won't be executed somehow, maybe somebody else comes up with how to execute latex code within 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: