1

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

我有一系列大约十几个 .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 文件加载到第二列的相应行中?

4

1 回答 1

2

这可以通过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)

在此处输入图像描述

于 2020-10-20T16:51:47.977 回答