r - 在 JS 或悬停操作中悬停在 flexdashboard 图上时显示工具提示

标签 r flexdashboard

我有以下示例 flexdashboard:

---
title: "Hover"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
library(tidyverse)
data(iris)
Column {data-width=650}
-----------------------------------------------------------------------

### Chart A

```{r}
iris %>% group_by(Species) %>% 
  summarise(mean = mean(Sepal.Length)) %>% 
  ggplot(aes(Species, mean)) + geom_col()

我想要的是将鼠标悬停在图中的条上并显示其值时的工具提示。我在 SO How do I show the y value on tooltip while hover in ggplot2 中阅读了这篇文章但它适用于 Shiny 。我试过这个:

p <- iris %>% group_by(Species) %>% 
  summarise(mean = mean(Sepal.Length))

labels <- sprintf("<strong>%s</strong><br/>Mean: %f", 
                     p$Species, p$mean) %>% 
     lapply(htmltools::HTML)

p %>% ggplot(aes(Species, mean)) + geom_col() + geom_text(aes(label = labels))

这会创建一个带有 specie 和值的 html 工具,我没有的是悬停(也许是 plot_hover?)来显示工具提示。

任何帮助将不胜感激

问候,

最佳答案

这是一个方法。您必须瞄准栏的顶部中心才能获得工具提示。

---
title: "Untitled"
runtime: shiny
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
---

```{r setup, include=FALSE}
library(flexdashboard)
library(dplyr)
library(ggplot2)
library(shiny)
```

Column {data-width=650}
-----------------------------------------------------------------------

### Chart A

```{r}
dat <- iris %>% group_by(Species) %>% 
  summarise(mean = mean(Sepal.Length))
output[["ggplot"]] <- renderPlot({
  dat %>% 
  ggplot(aes(Species, mean)) + geom_col()
})
output[["hoverinfo"]] <- renderUI({ 
  hover <- input[["plot_hover"]]
  if(is.null(hover)) return(NULL)
  point <- nearPoints(dat, hover, threshold = 50, maxpoints = 1)
  if(nrow(point) == 0) return(NULL)
  left_px <- hover$coords_css$x
  top_px <- hover$coords_css$y
  style <- 
    paste0("position:absolute; z-index:100; background-color: rgba(245, 245, 245, 0.85); ",
           "left:", left_px, 
           "px; top:", top_px, "px;")
  # tooltip created as wellPanel
  tooltip <- paste0(
    "<b> Species: </b>", point[["Species"]], "<br/>",
    "<b> mean: </b>", point[["mean"]]
  )
  wellPanel(
    style = style, p(HTML(tooltip))
  )
}) 
plotOutput("ggplot", hover = hoverOpts("plot_hover"))
div(uiOutput("hoverinfo"), style = "pointer-events: none;")
```

关于r - 在 JS 或悬停操作中悬停在 flexdashboard 图上时显示工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60401985/

相关文章:

r - 与 Reactable 结合使用时,串扰会使滚动条在 FlexDashboard 中不可见

r - Flexdashboard 宽表滚动到侧栏

r - 将不规则网格转换为规则网格

r - 将 dplyr 中的跨函数用于变量子集

r - 如何防止 data.table 在不手动指定这些的情况下将数字变量强制转换为字符变量?

r - 如何向 ggplot2 中的 geom_col 添加误差线?

shiny - flexdashboard 和 updateSelectInput ——对我来说不起作用

r - 用串扰过滤两个表

r - Shiny 的 Flexdashboard 响应式(Reactive)仪表未更新

r - 将月份第一级的值保留在数据框中,同时将 R 中的其余值设置为零