Coder’s Logbook

Some quick code snippets

Images

Stacking Images

More than one image can be read in to include_graphics() and the input can be explicit or vectorized. By adjusting the out.width, knitr will stack the images horizontally (if small enough) or vertically (if large enough).

Horizontally

```{r,echo=T,out.width="49%",fig.show='hold',fig.align='center',results='hide'}
knitr::include_graphics(c("path/to/img1.png","path/to/img2.png"))
``` 

Vertically

```{r,echo=T,out.width="75%",fig.show='hold',fig.align='center',results='hide'}
knitr::include_graphics("path/to/img1.png");
knitr::include_graphics("path/to/img2.png")
``` 

Hide Toolbar in Embedded PDF

Added 2/26/21

When embedding a PDF (in an iframe), add #toolbar=0 to the end of the link to hide the PDF toolbar.

<iframe src="http://dornshuld.chemistry.msstate.edu/files/cv.pdf#toolbar=0" 
width="100%" height="480"></iframe>

This can be processed by knitr for HTML vs. PDF outputs. The below example only embeds the iframe in the HTML output (won’t work for PDF).

if( knitr:::is_html_output() ) {
  cat ('<iframe src="http://dornshuld.chemistry.msstate.edu/files/cv.pdf#toolbar=0" 
       width="100%" height="480"></iframe>')
}

Magick + Knitr

Added 2/25/21

You can crop and scale an image read in from a URL via Knitr using Magick.

Code

library(magick)
crop <- function(im, left = 0, top = 0, right = 0, bottom = 0) {
  d <- dim(im[[1]]); w <- d[2]; h <- d[3]
  image_crop(im, glue::glue("{w-left-right}x{h-top-bottom}+{left}+{top}"))
}
"table2.png" %>%
  image_read() %>%
  crop(top=10, bottom = 250, left=340) %>%
  image_scale("800")

Before Crop

After Crop

Source