13.1 Crop plots
The chunk hook
knitr::hook_pdfcrop() can be used to crop PDF and other types of plot files, i.e., remove the extra margins in plots. To enable it, set this hook via
knit_hooks$set() in a code chunk, and turn on the corresponding chunk option, e.g.,
Then you can use the chunk option
crop = TRUE to crop plots in a code chunk.
hook_pdfcrop() calls the external program
pdfcrop to crop PDF files. This program often comes with a LaTeX distribution (e.g., TeX Live or MiKTeX). You can check if it is available in your system via:
## pdfcrop ## "/usr/local/bin/pdfcrop"
If you are using the LaTeX distribution TinyTeX (see Section 1.2), and
pdfcrop is not available in your system, you may install it via
For non-PDF plot files such as PNG or JPEG files, this hook function calls the R package magick (Ooms 2020) for cropping. You need to make sure this R package has been installed. Figure 13.1 shows a plot that is not cropped, and Figure 13.2 shows the same plot but has been cropped.
Ooms, Jeroen. 2020. Magick: Advanced Graphics and Image-Processing in R. https://CRAN.R-project.org/package=magick.