如何使 ggplot2 barplot 中的条形以闪亮的方式交互?

TMO*_*TTM 5 r ggplot2 shiny

我正在一个闪亮的应用程序中绘制 ggplot2 中的条形图。

在此输入图像描述

我想要的是,当鼠标悬停在其中一个栏上时,该栏会突出显示(可能是更强的轮廓),并且当我单击(或双击)该栏时,相应的 x 值可用作输入为一个textOutput

我试图在闪亮的文档中找到示例,但主要是关于从指针位置返回 x、y 值。有没有一个例子可以作为起点?

Big*_*ist 3

我有同样的问题并找到了这篇文章。我意识到这个问题已经很老了,但也许有人仍然对解决方案感兴趣。

挑战:

您面临的问题是 ggplot 将呈现为图像:在此输入图像描述

所以你没有可以监听的单独的 html 元素。

解决方案:

但闪亮的 ggplots 有一个有趣的功能。如果向图中添加单击侦听器,则$x单击事件的变量将缩放为图片中元素的数量。因此,如果您添加一个onlick侦听器,则该侦听器round($click$x)将等于被单击的元素。

请参阅此处的示例: https ://shiny.rstudio.com/articles/plot-interaction-advanced.html

可重现的例子:

我实现了一个带有文本框和突出显示的解决方案,突出显示部分来自突出显示 ggplot 中的单个“栏”

解决方案如下所示:

在此输入图像描述

样本数据:

letters <- data.frame(
  word = c("First", "Second", "Third"),
  num = c(2, 3, 4),
  stringsAsFactors = FALSE
)
Run Code Online (Sandbox Code Playgroud)

该应用程序:

library(shiny)
library(ggplot2)

ui <- fluidPage(
  fluidRow(
    column(6,
           plotOutput("plot1", click = "plot1_click")
    ),
    column(5,
           uiOutput("text")
    )
  )
)

server <- function(input, output) {
  global <- reactiveValues(toHighlight = rep(FALSE, length(letters$word)), 
    selectedBar = NULL)

  observeEvent(eventExpr = input$plot1_click, {
    global$selectedBar <- letters$word[round(input$plot1_click$x)]
    global$toHighlight <- letters$word %in% global$selectedBar
  })

  output$plot1 <- renderPlot({
    ggplot(data = letters, aes(x = word, y = num, fill = ifelse(global$toHighlight, 
      yes = "yes", no = "no"))) +
      geom_bar(stat="identity") +
      scale_fill_manual(values = c("yes" = "blue", "no" = "grey" ), guide = FALSE )
  })

  output$text <- renderUI({
    req(global$selectedBar)
    textInput(inputId = "label", label = "selected text:", value = global$selectedBar)
  })
}
shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)