2

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?

jerH
  • 1,085
  • 1
  • 12
  • 30

1 Answers1

3

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

stefan
  • 90,330
  • 6
  • 25
  • 51
  • This was great...thanks so much. Don't suppose you could answer this one? :) https://stackoverflow.com/questions/64359096/saving-an-echarts4r-image-via-code-again – jerH Oct 20 '20 at 20:24
  • You are welcome. Concerning your second question. I'm afraid I can't help you with that. Actually I already had a look at this question some days ago but wasn't able to find a solution. ): Best S. – stefan Oct 21 '20 at 07:52