2

我已经寻找一种方法来创建一个带有徽标/图像的表作为数据表的列。我附上了一张我想要的那种桌子的图片。数据表取自一个使用 的示例library(formattable),我在“id”列顶部粘贴了徽标,以显示我正在寻找的设计类型。理想情况下,这会更整洁和可定制(也许整个表格背景都是黑色的,带有白色/灰色文字等。有没有人可以分享任何示例?

带有徽标的桌子

创建不带徽标的可格式化表格的代码:

df <- data.frame(
  id = 1:10,
  name = c("Bob", "Ashley", "James", "David", "Jenny", 
    "Hans", "Leo", "John", "Emily", "Lee"), 
  age = c(28, 27, 30, 28, 29, 29, 27, 27, 31, 30),
  grade = c("C", "A", "A", "C", "B", "B", "B", "A", "C", "C"),
  test1_score = c(8.9, 9.5, 9.6, 8.9, 9.1, 9.3, 9.3, 9.9, 8.5, 8.6),
  test2_score = c(9.1, 9.1, 9.2, 9.1, 8.9, 8.5, 9.2, 9.3, 9.1, 8.8),
  final_score = c(9, 9.3, 9.4, 9, 9, 8.9, 9.25, 9.6, 8.8, 8.7),
  registered = c(TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE),
  stringsAsFactors = FALSE)


formattable(df, list(
  age = color_tile("white", "orange"),
  grade = formatter("span", style = x ~ ifelse(x == "A", 
                                               style(color = "green", font.weight = "bold"), NA)),
  area(col = c(test1_score, test2_score)) ~ normalize_bar("pink", 0.2),
  final_score = formatter("span",
                          style = x ~ style(color = ifelse(rank(-x) <= 3, "green", "gray")),
                          x ~ sprintf("%.2f (rank: %02d)", x, rank(-x))),
  registered = formatter("span",
                         style = x ~ style(color = ifelse(x, "green", "red")),
                         x ~ icontext(ifelse(x, "ok", "remove"), ifelse(x, "Yes", "No")))
))
4

1 回答 1

5

您可以构建自己的列处理程序。例如,

library(tidyverse)
library(formattable)

image_tile <- formatter("img",
                        src = x ~ ifelse(x == "test", "path/to/image", "path/to/image"),
                        NA)

formattable(df, list(id = image_tile))

在此处输入图像描述

您可以更改path/to/image不同图像的位置;或者,您可以使用更复杂的功能(例如使用recode)。

嵌入图像似乎更棘手——这绝不是最好的答案,但它确实有效。但是,它每次都会复制图像,从而使 HTML 膨胀。

您可以使用本地路径,然后保存为 HTML。

library(base64enc)

image1 <- sprintf("data:image/png;base64,%s", base64encode("image-1.png"))
image2 <- sprintf("data:image/png;base64,%s", base64encode("image-2.png"))

image_tile <- formatter("img",
                        src = x ~ ifelse(x > 5, image1, image2),
                        # Control height and width, either directly - 
                        width = 50, 
                        # Or via a formula
                        height = x ~ ifelse(x > 5, 10, 50),
                        NA)

formattable(df, list(id = image_tile))

在此处输入图像描述

于 2016-11-29T17:04:24.663 回答