Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

local_image

Helper function for adding a local image


Description

We can flexibly add a local image (i.e., an image residing on disk) inside of a table with local_image() function. The function provides a convenient way to generate an HTML fragment using an on-disk PNG or SVG. Because this function is currently HTML-based, it is only useful for HTML table output. To use this function inside of data cells, it is recommended that the text_transform() function is used. With that function, we can specify which data cells to target and then include a local_image() call within the required user-defined function (for the fn argument). If we want to include an image in other places (e.g., in the header, within footnote text, etc.) we need to use local_image() within the html() helper function.

Usage

local_image(filename, height = 30)

Arguments

filename

A path to an image file.

height

The absolute height (px) of the image in the table cell.

Details

By itself, the function creates an HTML image tag with an image URI embedded within. We can easily experiment with a local PNG or SVG image that's available in the gt package using the test_image() function. Using that, the call local_image(file = test_image(type = "png")) evaluates to:

<img cid=<random CID> src=<data URI> style=\"height:30px;\">

where a height of 30px is a default height chosen to work well within the heights of most table rows.

Value

A character object with an HTML fragment that can be placed inside of a cell.

Figures

Function ID

8-2

See Also

Other Image Addition Functions: ggplot_image(), test_image(), web_image()

Examples

# Create a tibble that contains heights
# of an image in pixels (one column as a
# string, the other as numerical values),
# then, create a gt table; use the
# `text_transform()` function to insert
# a local test image (PNG) image with the
# various sizes
tab_1 <-
  dplyr::tibble(
    pixels = px(seq(10, 35, 5)),
    image = seq(10, 35, 5)
  ) %>%
  gt() %>%
  text_transform(
    locations = cells_body(vars(image)),
    fn = function(x) {
      local_image(
        filename = test_image(type = "png"),
        height = as.numeric(x)
      )
    }
  )

gt

Easily Create Presentation-Ready Display Tables

v0.2.2
MIT + file LICENSE
Authors
Richard Iannone [aut, cre] (<https://orcid.org/0000-0003-3925-190X>), Joe Cheng [aut], Barret Schloerke [aut] (<https://orcid.org/0000-0001-9986-114X>), RStudio [cph, fnd]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.