11.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 to crop them. You need to make sure this R package has been installed. Figure 11.1 shows a plot that is not cropped, and Figure 11.2 shows the same plot but has been cropped.