为 ggiraph 的交互式工具提示格式化 table 的最简单方法

Easiest way to format table for interactive tooltip for ggiraph

我在下面有这个基本示例。正如您将看到的那样,它是一个交互式情节。我现在希望实现的是当您将鼠标悬停在数据点上时,将 dummy_data 设为工具提示的格式化 table 。我将有不同的积分集,但 我只想让这个示例适用于所有人,然后我可以更改数据。

正如您将在 tooltip = 参数中看到的那样,它需要包含在此处。我只是不确定是否有一种简单的方法来传递此 table,因为它打印在其中并带有一些 css 以便轻松地对其进行格式化。我希望它看起来与打印到控制台的 dummy_data 一样好或更好。

我希望这已经足够清楚了吧?如果我可以澄清,请告诉我。请参阅下面的 reprex。

library(ggplot2)
library(ggiraph)
#> Warning: package 'ggiraph' was built under R version 4.1.2


dataset <- mtcars

dummy_data <- 
  data.frame(
    stringsAsFactors = FALSE,
    Feature = c("FeatureA","FeatureB",
                "FeatureC","FeatureD","FeatureE","FeatureF","FeatureG",
                "FeatureH","FeatureI","FeatureJ","FeatureK","FeatureL",
                "FeatureM","FeatureN","FeatureO","FeatureP","FeatureQ",
                "FeatureR","FeatureS","FeatureT","FeatureU"),
    Rating = c(1L,1L,1L,1L,3L,3L,4L,1L,
               4L,1L,4L,1L,1L,1L,1L,4L,1L,1L,2L,3L,2L)
  )

dummy_data
#>     Feature Rating
#> 1  FeatureA      1
#> 2  FeatureB      1
#> 3  FeatureC      1
#> 4  FeatureD      1
#> 5  FeatureE      3
#> 6  FeatureF      3
#> 7  FeatureG      4
#> 8  FeatureH      1
#> 9  FeatureI      4
#> 10 FeatureJ      1
#> 11 FeatureK      4
#> 12 FeatureL      1
#> 13 FeatureM      1
#> 14 FeatureN      1
#> 15 FeatureO      1
#> 16 FeatureP      4
#> 17 FeatureQ      1
#> 18 FeatureR      1
#> 19 FeatureS      2
#> 20 FeatureT      3
#> 21 FeatureU      2

dataset$carname <- row.names(dataset)
dataset$tooltip <- paste(dummy_data)



gg_scatter <- ggplot(dataset, 
                     aes(x = disp, y = qsec, tooltip = 
                           paste0(
                             "<div class='header' checked>
                           <p>Ready to take ",tooltip,"? If so</p>
                           <a href='shiny.rstudio.com/tutorial'>Click Here!</a>
                           </div>"), 
                         data_id = carname, color= wt) ) + 
  geom_point_interactive(size=3) + 
  labs(title = "mouse over points") + 
  theme_minimal() + theme(
    plot.background = element_blank(),
    panel.background = element_blank()
  )



girafe(ggobj = gg_scatter, 
       options = list(
         opts_sizing(rescale = TRUE, width = .7) )
)

reprex package (v2.0.0)

于 2022-04-27 创建

您可以将 HTML 代码传递给工具提示,因此一种方法是使用 knitr::kable 创建 table 的 HTML 版本,获取 HTML table 代码并将其添加到您的数据框中,然后用作工具提示。

library(ggplot2)
library(ggiraph)

dataset <- mtcars

# add tooltip, using only first 10 rows to avoid showing too much text
dataset$tooltip <- knitr::kable(dummy_data[1:10, ], format = "html")

gg_scatter <- ggplot(dataset, 
                     aes(x = disp, y = qsec, 
                         tooltip = tooltip, color= wt) ) + 
    geom_point_interactive(size=3) 

girafe(ggobj = gg_scatter)

要对工具提示 table 进行更多自定义,而不是 knitr::kable,您可以使用其他一些允许创建更多自定义 HTML table 的包。