29 Embedding images
There are a few ways to embed images in a plotly graph. Perhaps the easiest is to point the image source to a hyperlink containing a bitmap file (e.g., png, jpeg, tiff, etc).
The approach in Figure 29.1 has a downside though – if that hyperlink breaks, then so does your plot. It’d be better to download the file to your machine and use the
dataURI() function from the base64enc package (or similar) to embed the image as a data URI (Urbanek 2015).
Another approach is to convert a raster object into a data URI, which the
raster2uri() function in plotly is designed to do. R actually ships with native support for raster objects and many image processing R packages either build on this data structure or provide a utility to convert to a raster object (perhaps via
as.raster()). For example, the
readPNG() function from the png package reads image data in an R array, which can be converted to a raster object (Urbanek 2013).
Moreover, thanks to the R package magick it’s possible to rasterize non-raster file formats (e.g., pdf, svg, etc) directly in R, so if you wanted, you could also embed non-bitmap images by using
image_convert() to generate a raster object (Ooms 2019).
Ooms, Jeroen. 2019. Magick: Advanced Graphics and Image-Processing in R. https://github.com/ropensci/magick#readme.
Urbanek, Simon. 2013. Png: Read and Write Png Images. https://CRAN.R-project.org/package=png.
Urbanek, Simon. 2015. Base64enc: Tools for Base64 Encoding. https://CRAN.R-project.org/package=base64enc.