【问题标题】:Insert images into gt table将图像插入 gt 表
【发布时间】:2020-10-21 00:51:47
【问题描述】:

我对如何使用gt 包中的text_transformlocal_image 函数将图像插入数据单元格有点困惑

我有一系列大约十几个 .png 文件,其中包含我想要插入的图形。它们的名称为 CA.png、UT.png、OH.png 等,用于州缩写。它们都在一个本地文件夹中。

所以给定一个基本的表格

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)

如何将 png 文件加载到第二列的相应行中?

【问题讨论】:

    标签: r image gt


    【解决方案1】:

    这可以通过gt 函数text_transformlocal_image 来实现,如下所示:

    1. text_transform 转换列的内容时,将文件名放在第二列中。
    2. 对于函数参数.fn,将函数传递给text_transform 以循环遍历列元素,通过local_image 加载和转换图像并返回一个字符向量。

    利用purrrggplot2,下面的代码首先让一些示例ggplots 将它们保存为png,最后将它们添加到您的第二列:

    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)
    

    【讨论】:

    • 这太棒了...非常感谢。不知道你能回答这个问题吗? :) stackoverflow.com/questions/64359096/…
    • 不客气。关于你的第二个问题。恐怕我帮不了你。实际上我几天前已经看过这个问题,但无法找到解决方案。 ): 最佳 S.
    猜你喜欢
    • 2017-12-02
    • 2013-03-21
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多