2

How can I align a kable table to be adjacent to a ggplot2 plot in an rmarkdown html_document?

Foo.Rmd

---
title: "Foo"
output: html_document
---

```{r setup, include=FALSE}
library(ggplot2)
library(knitr)
library(kableExtra)
```

# Table next to plot
```{r echo = FALSE}
kable(head(iris)) %>%
  kable_styling(bootstrap_options = "striped", full_width = F)

ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()
```

enter image description here

I tried following the solution here but to no avail.

Ben
  • 20,038
  • 30
  • 112
  • 189
  • 1
    Possible duplicate of [A Kableextra table and a ggplot plot on same row in Rmarkdown (PDF - not Flexdashboard)](https://stackoverflow.com/questions/50858351/a-kableextra-table-and-a-ggplot-plot-on-same-row-in-rmarkdown-pdf-not-flexdas) – pogibas Jan 22 '19 at 16:53
  • Hmm, that is definitely a similar question but I saw that question as distinctively different since it asks about aligning a table and plot within a *pdf_document*, not an *html_document* as in my case. (Not to mention, the sole answer will not work for my needs since it does not use kable.) – Ben Jan 22 '19 at 18:10

1 Answers1

13

A great solution to this issue is provided here by @ErrantBard: https://stackoverflow.com/a/40650190/645206. Please visit and upvote it! I am copying the solution in my answer to show how it works with your example, and to provide an image of the solution.

To better understand how these div tags work, learn more about the bootstrap library. Here is one good link: https://getbootstrap.com/docs/4.1/layout/grid/

---
title: "Foo"
output: html_document
---

```{r setup, include=FALSE}
library(ggplot2)
library(knitr)
library(kableExtra)
```

# Table next to plot
<div class = "row">
<div class = "col-md-6">
```{r echo=FALSE}
kable(head(iris)) %>%
  kable_styling(bootstrap_options = "striped", full_width = FALSE, position="left")
```
</div>

<div class = "col-md-6">
```{r echo=FALSE}
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()
```
</div>
</div>

enter image description here

bdemarest
  • 14,397
  • 3
  • 53
  • 56
  • 2
    This helped so much! Btw, if the table is much longer than the plot, is there a way to make the table shorter, i.e. crop the table in some way? – Helen May 29 '19 at 12:28
  • 1
    or if that is impossible, align the two plots horizontally? – Helen May 29 '19 at 13:42
  • 1
    Is it possible to make it only in one chunk?. I would like to make many inside a loop but to do that I need it to be in one single chunk I guess. – Francisco Mar 18 '20 at 14:43