如何在shiny中使ggplot2条形图上的条形变得可交互?

5

我正在一个shiny应用程序中使用ggplot2绘制条形图。

enter image description here

当鼠标悬停在其中一根条形图上时,我希望该条形图会突出显示(可能是加强轮廓),当我单击(或双击)该条形图时,相应的x值就可用作textOutput的输入。我尝试在闪亮的文档中找到例子,但那里大多是关于从指针位置返回x和y值的。有没有一个示例可以作为起点?

你只需要 ggplot2 的解决方案吗?如果不是,你也可以看看 rcharts - NicE
目前最好使用ggplot2,因为我更熟悉它。 - TMOTTM
1
@nongkrong 看看这个链接(http://blog.rstudio.org/2015/06/16/shiny-0-12-interactive-plots-with-ggplot2/),虽然不是最佳答案... - NicE
1
@NicE,太酷了!谢谢你 :) - Rorschach
@nongkrong 说得好。我想只有使用 JavaScript 绘图才可能实现。 - TMOTTM
显示剩余3条评论
1个回答

3

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

挑战:

你面临的问题是ggplot将被呈现为图像:enter image description here

因此你没有单独的HTML元素可以监听。

解决方案:

但是,在shiny的ggplots中有一个有趣的功能。如果你向绘图添加一个点击监听器,则单击事件的$x变量将缩放到图片中的元素数量。因此,如果你添加了一个onlick监听器,则round($click$x)将等于被单击的元素。

在这里查看示例: https://shiny.rstudio.com/articles/plot-interaction-advanced.html

可重复的例子:

我使用文本框和高亮显示实现了一种解决方案,其中高亮显示部分来自Highlight a single "bar" in ggplot

解决方案如下:

enter image description here

样本数据:

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

该应用程序:
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)

1
干得好,Tonio,谢谢你。 - Douglas Wiley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接