R Shiny Plot Click with geom bar and facets

Nic*_*ell 1 r ggplot2 shiny

我想用shiny和创建一个交互式绘图ggplot2。我已经能够与成功做到这一点geom_point和其他geoms明显带有xy轴。geom_bar但是,当使用 a 之类的东西时,这更难,因为您没有y变量。

这里这里有一个解决方案,可以x从点击事件中提取变量来进行所需的过滤,但这些都没有处理带有刻面的图。我想在ggplot带有刻面的a 上使用单击选项。我试图在第一个链接处修改代码,但这并没有成功。

library(ggplot2)
library(shiny)

ui <- fluidPage(
  fluidRow(
    plotOutput("plot1", height = 300, width = 300,
               click = "plot1_click",
    )
  ),
  verbatimTextOutput("x_value"),
  verbatimTextOutput("selected_rows")
)

server <- function(input, output) {
  output$plot1 <- renderPlot({
    ggplot(ToothGrowth, aes(supp)) + geom_bar(stat = "count") + facet_wrap(~dose)
  })

  # Print the name of the x value
  output$x_value <- renderPrint({
    if (is.null(input$plot1_click$x)) return()

    lvls <- levels(ToothGrowth$supp)
    lvls[round(input$plot1_click$x)]
  })

  # Print the rows of the data frame which match the x value
  output$selected_rows <- renderPrint({
    if (is.null(input$plot1_click$x)) return()

    keeprows <- round(input$plot1_click$x) == as.numeric(ToothGrowth$supp)
    ToothGrowth[keeprows, ]
  })
}

shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)

单击任何条形可以很好地过滤到x值,但包括所有方面的结果。我只想包括来自点击方面的结果。

在此处输入图片说明

我曾尝试使用nearPointswithpannelvar1但它会引发错误,因为我没有y要传递给它的变量。

有什么想法吗?

dan*_*son 5

我改变了你的最后一个函数并得到了我认为你想要的结果。

  output$selected_rows <- renderPrint({
    if (is.null(input$plot1_click$x)) return()
    panel = input$plot1_click$panelvar1

    keeprows <- round(input$plot1_click$x) == as.numeric(ToothGrowth$supp) & ToothGrowth$dose==panel
    ToothGrowth[keeprows, ]
  })
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我不确定您在尝试访问 panelvar1 时遇到了什么错误,但我使用配置选项options(shiny.trace=TRUE)来检查如何访问面板变量(下面添加了日志消息)。也许你只是想从错误的位置拉取价值

RECV {"method":"update","data":{"plot1_click":{"x":1.1651034873830555,"y":4.268063179119527,"panelvar1":2,"mapping":{"x":"supp","y":null,"panelvar1":"dose"},"domain":{"left":0.4,"right":2.6,"bottom":-0.5,"top":10.5},"range":{"left":213.995433789954,"right":294.520547945205,"bottom":268.013698630137,"top":23.4383561643836},"log":{"x":null,"y":null},".nonce":0.39996409229934216}}}
Run Code Online (Sandbox Code Playgroud)