Skip to contents

Evaluates a plotting expression in a temporary PNG device and returns the resulting image as a self-contained, base64-encoded <img> tag (class "html", see asHtml()), suitable for embedding directly in HTML text – a report, a question, an e-mail.

Usage

asImg(expr, width = 520, height = 440, res = 96, ...)

Arguments

expr

a plotting expression, evaluated once inside the device. A character string is not accepted: pass the plotting code itself, e.g. asImg(plot(1:10)) instead of asImg("plot(1:10)").

width, height

size of the device in pixels

res

nominal resolution in dpi, which also scales the text: raise it for a larger picture with the same relative proportions

...

further arguments passed to grDevices::png()

Value

an object of class c("html", "character") containing an <img> tag with a data:image/png;base64,... source

Details

The expression is passed unevaluated and carries its own environment, so a plot built inside a function sees that function's local variables. Several statements are given in braces, as in the examples below.

Examples

img <- asImg(plot(1:10))

# several statements, and local variables
f <- function(n) {
  x <- seq_len(n)
  asImg({
    plot(x, x^2, type = "b")
    abline(h = mean(x^2), lty = 2)
  })
}
substr(f(10), 1, 30)
#> <img src="data:image/png;base6