Is there a way to keep full margins in ggplot2 pdf output?

こ雲淡風輕ζ 提交于 2020-04-16 05:47:10

问题


In this answer https://stackoverflow.com/a/61017301/2554330 I partially answered a problem in resizing subfigures in ggplot2 output using code similar to this:

---
title: "Untitled"
header-includes:
   - \usepackage{subcaption}
output: 
  pdf_document:
    keep_tex: TRUE
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{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 = unit(c(1,0,1,0),"in") + theme_get()$plot.margin)
p2 + theme(plot.margin = unit(c(1/2,0,1/2,0),"in") + theme_get()$plot.margin)
p3
```

This produces this output:

Notice how there is no bottom margin in the first and second plots, even though I requested equal top and bottom margins. If I look at the actual .pdf files in the figure directory, I can see that they don't contain any margins at all: the file seems to have been cropped to the edge of the bounding box of the ink on the page, so the first plot is (according to Acrobat "Document Properties") 0.83in by 0.83in, the second is 0.83in by 1.83in, and the last one is 0.83in by 2.83in.

What I'd expect to get is to have each of the three plots vertically centred within the 1in by 3in size that I requested. The PDF files should all be that size.

Is there a way to suppress this cropping?


回答1:


After looking through the knitr and rmarkdown source code for a while, I've found the answer. The rmarkdown::pdf_document output function has an argument fig_crop that defaults to TRUE. Setting it to FALSE suppresses cropping of figures in the whole document. So all I need to do in this example is change my header YAML to include

output: 
  pdf_document:
    fig_crop: FALSE

and the problem is solved. As far as I know there is no chunk-level option to change this: all figures are cropped, or none are.



来源:https://stackoverflow.com/questions/61029336/is-there-a-way-to-keep-full-margins-in-ggplot2-pdf-output

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