R Markdown - Positioning table and plot side by side

末鹿安然 提交于 2021-02-14 14:01:43

问题


I am using R Markdown to output to pdf, and I am trying to get a table and a plot aligned side by side horizontally. I can get fig.align = "right" to align the plot to the right of the page, but it is plotted under the table (formatted with kable) and not side by side with it. Any tips?


回答1:


Here is a way using the TeX package floatrow:

---
title: "Untitled"
header-includes:
  - \usepackage{floatrow}
output: 
  pdf_document:
    keep_tex: true
---

\newfloatcommand{btabbox}{table}

\begin{figure}[H]
  \begin{floatrow}
    \ffigbox{%
```{r, fig.align = "right", echo = F}
plot(mpg ~ hp, data = mtcars)
```
    }{\caption{A figure}}

    \btabbox{%
```{r, fig.align = "right", echo = F}
knitr::kable(head(mtcars[,1:3]), format = "latex")
```
    }{\caption{A table}}
  \end{floatrow}
\end{figure}




回答2:


I prefer the method by Martin, but if you wanted to have a less LaTeX reliant solution, you could convert the table into a grid graphic and plot it as a subfigure:

---
header-includes:
  - \usepackage{subfig}
output: pdf_document
---

```{r, fig.cap='two plots', fig.subcap= c('A figure', 'A table'), out.width = '.49\\linewidth', echo = F, fig.align='center'}
library(gridExtra)
library(grid)

plot(mpg ~ hp, data = mtcars)

grid.newpage()
grid.table(head(mtcars[,1:6]), theme = ttheme_minimal())
```




回答3:


I was able to do this with a combination of the multicol package and minipages. Just another option...

Here's the code:

---
title: "Untitled"
header-includes:
  - \usepackage{multicol}
  - \newcommand{\btwocol}{\begin{multicols}{2}}
  - \newcommand{\etwocol}{\end{multicols}}
output: 
  pdf_document:
    keep_tex: true
---

```{r minipage_funs, echo = FALSE}
## adding minipages in Rmarkdown only seems to work for me when returned from function
fig_table_mp_start <- function() {
  return("\\begin{minipage}{\\textwidth}")
}
fig_table_mp_end <- function() {
  return("\\end{minipage}")
}
```

`r fig_table_mp_start()`

\btwocol

```{r, fig.align = "right", echo = FALSE}
plot(mpg ~ hp, data = mtcars)
```


```{r, fig.align = "right", echo = FALSE}
knitr::kable(head(mtcars[,1:3]), format = "latex")
```

\etwocol

`r fig_table_mp_end()`

I assume you can play around with padding to make it look pretty.



来源:https://stackoverflow.com/questions/53659160/r-markdown-positioning-table-and-plot-side-by-side

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!