在Rmarkdown中对齐表格和绘图

时间:2020-03-26 10:48:15

标签: r ggplot2 r-markdown knitr kable

我想在绘图旁边放置一个表格(绘图基于表格),理想情况下将表格行与绘图的刻度对齐。目前,我正在玩theme(plot.margin)fig.height来尝试手动执行,结果还可以,但是一旦发生变化(向图中添加图例或向表中添加行),我就必须重新重申。

是否有更好的方法可以更自动化地获得相同的结果?也许将表格添加到情节中?

屏幕截图

手动对齐 Aligned

无需手动对齐 Unaligned

代码

---
output: html_document
---

```{r setup, include = FALSE}
library(kableExtra)
library(tibble)
library(dplyr)
library(ggplot2)
knitr::opts_chunk$set(echo = FALSE,
                      message = FALSE,
                      warning = FALSE,
                      fig.align = "center")
```

<div class = "row">
<div class = "col-md-3">
```{r}
raw_dat <- mtcars[1:15, ] %>% rownames_to_column(var = "id") %>% select(id, mpg)
kable(raw_dat) %>%
   kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive"),
                 full_width = FALSE)
```
</div>
<div class = "col-md-9">
```{r, fig.height=5.5}
   ggplot(raw_dat, aes(factor(id, rev(id)), mpg)) +
   geom_point() +
   coord_flip() +
   theme(plot.margin = margin(0.6, unit = "cm"))
```
</div>
</div>

0 个答案:

没有答案