Rmarkdown / knitr subfigure different figure sizes

断了今生、忘了曾经 提交于 2020-04-16 04:04:14

问题


I am trying to achieve different heights and widths for subfigures in Rmarkdown. I was hoping that just providing fig.height and fig.width with a vector each would work, as this does seem to work for out.height and out.width

---
title: "Untitled"
output: pdf_document
header-includes:
   - \usepackage{subfig}
---



```{r, echo = FALSE, fig.height = c(1,2,3), fig.width=c(1,1,1), fig.cap='Caption', fig.subcap=c('Subcaption 1', 'Subcaption 2', 'Subcaption 3')}
library(ggplot2)
df <- data.frame(
  x = rnorm(30),
  y = rnorm(30)
)
p1 <- p2 <- p3 <- ggplot(df, aes(x, y)) +
  geom_point()

print(p1)

print(p2)

print(p3)
```

However, the result is this

So, it seems that all subfigures use the values fig.height = 3, fig.width= 1

Does somebody know how to specify those value for each subfigure separately?


回答1:


Those aren't really "subfigures", they are just side-by-side figures. So you can get what you want with some more typing:

```{r, echo = FALSE}
library(ggplot2)
df <- data.frame(
  x = rnorm(30),
  y = rnorm(30)
)
p1 <- p2 <- p3 <- ggplot(df, aes(x, y)) + geom_point()
```
```{r echo = FALSE, fig.height=1, fig.width=1}
print(p1)
```
```{r echo = FALSE, fig.height=2, fig.width=1}
print(p2)
```
```{r echo = FALSE, fig.height=3, fig.width=1}
print(p3)
```

You could probably automate this a little using ideas from https://yihui.org/knitr/demo/reference/, but I'm not sure it's worth the trouble. Another promising approach would be to use the gridExtra::grid.arrange function, though I'm not sure if it would allow the layout you want.

EDITED TO ADD after the comment indicating that true LaTeX subfigures are wanted:

This is harder, because as you saw, fig.height is not treated separately for each subfigure. I think you can get the heights you want by adding extra margins. To have full control over vertical centering, you need to turn off cropping of the figures using the YAML option

output: 
  pdf_document:
    fig_crop: FALSE

With that option this code

```{r, echo = FALSE, fig.height=3, fig.width=1,fig.subcap=c("first", "second", "third"),fig.cap="Main"}
library(ggplot2)
df <- data.frame(
  x = rnorm(30),
  y = rnorm(30)
)
p1 <- p2 <- p3 <- ggplot(df, aes(x, y)) + geom_point()
p1 + theme(plot.margin = margin(t = 1, b = 1, unit = "in") + theme_get()$plot.margin)
p2 + theme(plot.margin = margin(t = 1/2, b = 1/2, unit = "in") + theme_get()$plot.margin)
p3
```

gives this output:



来源:https://stackoverflow.com/questions/61015431/rmarkdown-knitr-subfigure-different-figure-sizes

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