knitr (version 1.1)

hook_rgl: Built-in chunk hooks to extend knitr

Description

Hook functions are called when the corresponding chunk options are not NULL to do additional jobs beside the R code in chunks. This package provides a few useful hooks, which can also serve as examples of how to define chunk hooks in knitr.

Usage

hook_rgl(before, options, envir)

hook_pdfcrop(before, options, envir)

hook_optipng(before, options, envir)

hook_plot_custom(before, options, envir)

hook_webgl(before, options, envir)

Arguments

before,options,envir
see references

Details

The function hook_rgl can be set as a hook in knitr to save plots produced by the rgl package. According to the chunk option dev (graphical device), plots can be save to different formats (postscript: eps; pdf: pdf; other devices correspond to the default PNG format). The plot window will be adjusted according to chunk options fig.width and fig.height. Filenames are derived from chunk labels and the fig.path option.

The function hook_webgl is a wrapper for the writeWebGL() function in the rgl package. It writes WebGL code to the output to reproduce the rgl scene in a browser.

The function hook_pdfcrop can use the program pdfcrop to crop the extra white margin when the plot format is PDF to make better use of the space in the output document, otherwise we often have to struggle with par to set appropriate margins. Note pdfcrop often comes with a LaTeX distribution such as MiKTeX or TeXLive, and you may not need to install it separately (use Sys.which('pdfcrop') to check it; if it not empty, you are able to use it). Similarly, when the plot format is not PDF (e.g. PNG), the program convert in ImageMagick is used to trim the white margins (call convert input -trim output).

The function hook_optipng calls the program optipng to optimize PNG images. Note the chunk option optipng can be used to provide additional parameters to the program optipng, e.g. optipng = '-o7'. See http://optipng.sourceforge.net/ for details.

When the plots are not recordable via recordPlot and we save the plots to files manually via other functions (e.g. rgl plots), we can use the chunk hook hook_plot_custom to help write code for graphics output into the output document.

References

http://yihui.name/knitr/hooks#chunk_hooks

See Also

rgl.snapshot, rgl.postscript

Examples

Run this code
knit_hooks$set(rgl = hook_rgl)
## then in code chunks, use the option rgl=TRUE

Run the code above in your browser using DataCamp Workspace