Search code examples
rimagegt

Insert images into gt table


I'm a little confused on how to use the text_transform and local_image function in the gt package to insert images into a data cell

I have a series of about a dozen .png files with the graphics I'd like to insert. They have names like CA.png, UT.png, OH.png etc. for state abbreviations. They are all together in a local folder.

So given a basic table like

library(gt)
library(magrittr)

Column_one <- c("CA", "UT", "OH")
column_two <- c(NA, NA, NA)    #placeholder for graphics

dashboard.data <- data.frame(column_one, column_two, stringsAsFactors = FALSE)

names(dashboard.data)[1] <- "State"
names(dashboard.data)[2] <- "IncidenceGauge"

dboard3 <- dashboard.data %>% gt() %>%
  tab_header(
    title = md("**Big Title**"),
    subtitle = md("*Subtitle*")
  ) %>%
  cols_label(IncidenceGauge = "Risk Level") %>%
  
  print(dboard3)

How would I go about getting the png files loaded into the corresponding rows in column two?


Solution

  • This could be achieved via gt functions text_transform and local_image like so:

    1. As text_transform transforms the content of a column put the filenames in your second column.
    2. For the function argument .fn pass a function to text_transform to loop over the column elements, loads and transforms the images via local_image and returns a character vector.

    Making use of purrr and ggplot2 the following code first makes some example ggplots saves them as png and finally adds them to your second column:

    library(gt)
    library(magrittr)
    library(purrr)
    library(ggplot2)
    
    # Let's make some pngs
    mtcars %>% 
      split(.$cyl) %>% 
      map(~ ggplot(.x, aes(hp, mpg, color = factor(gear))) + geom_point()) %>% 
      set_names(c("CA", "UT", "OH")) %>% 
      iwalk(~ ggsave(paste0(.y, ".png"), .x))
    
    column_one <- c("CA", "UT", "OH")
    # Put the filenames in the column
    column_two <- c("CA", "UT", "OH")
    
    dashboard.data <- data.frame(column_one, column_two, stringsAsFactors = FALSE)
    
    names(dashboard.data)[1] <- "State"
    names(dashboard.data)[2] <- "IncidenceGauge"
    
    dboard3 <- dashboard.data %>% 
      gt() %>%
      tab_header(
        title = md("**Big Title**"),
        subtitle = md("*Subtitle*")
      ) %>%
      text_transform(
        locations = cells_body(vars(IncidenceGauge)),
        fn = function(x) {
          # loop over the elements of the column
          map_chr(x, ~ local_image(
            filename = paste0(.x, ".png"),
            height = 100
          ))
        }) %>% 
      cols_label(IncidenceGauge = "Risk Level")
        
    print(dboard3)
    

    enter image description here