问题
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