Reputation: 59
I have the following Rmarkdown Trial:
---
title: "Test kableExtra"
date: "3/20/2021"
output: pdf_document
classoption: landscape
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(kableExtra)
```
# R Markdown
```{r echo=FALSE}
library(knitr)
library(xtable)
dt <- mtcars[1:5, 1:6]
t1 <- kbl(dt, booktabs = T)
t2 <- kbl(dt, booktabs = T)
t3 <- ggplot(dt,aes(x=mpg,y=cyl)) +
geom_point()
png(file="plot1.png",width=200,height=200)
print(t3)
dev.off() # close the png file
```
Some Text
\begin{table}[!h]
\begin{minipage}{.5\linewidth}
\centering
```{r echo=FALSE}
t1
```
\end{minipage}%
\begin{minipage}{.5\linewidth}
\centering
\includegraphics[width=\textwidth]{plot1.png}
\end{minipage}
\end{table}
And when you knit it it works ok, but I would like the graph and the table to be aligned on top. Anybody an idea?
If you have a better idea to put a ggplot next to a kbl table I'm all ears!
Thanks, Michael
Upvotes: 3
Views: 528
Reputation: 513
The following code might help:
---
title: "Test kableExtra"
date: "3/20/2021"
output: pdf_document
header-includes:
- \usepackage{multicol}
- \newcommand{\btwocol}{\begin{multicols}{2}}
- \newcommand{\etwocol}{\end{multicols}}
classoption: landscape
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(kableExtra)
```
# R Markdown
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est laborum.
\btwocol
```{r echo=FALSE, results="asis", message=FALSE}
# sample data
dt <- mtcars[1:5, 1:6]
# create the table
t1 <- kable(dt, booktabs = TRUE)
# create the plot
t3 <- ggplot(dt,aes(x=mpg, y=cyl)) +
geom_point()
# print the table
print(t1)
cat("\\columnbreak")
# print the plot
print(t3)
cat("\\pagebreak")
```
\etwocol
Notes:
Conceptually the solution is presented in the accepted answer here; however, I couldn't reproduce the code there.
I stripped down your initial code to leave a minimal example. That is, I removed the code for table t2
and the calls for library(knitr)
and library(xtable)
.
Other changes to your initial code include:
The call for LaTeX packages and commands under header-includes
in the YAML section of your Rmd file
The addition of some lorem ipsum text to see more clearly how objects are aligned with respect to one another
Setting results="asis"
in the R code chunk that generates the table and the plot
The use of function kable()
instead of kbl()
. If you use kbl()
the table is a little bit off with respect to the plot (I don't know why). I recommend you to play with both functions
Upvotes: 2