shiny - Plotly 和 Shiny:onclick 切换选项卡以创建情节
问题描述
我创建了一个简单的图,当用户单击一个点时,它会在第二个选项卡上生成另一个图,Page_2
是否可以添加一些自定义 JS,以便当用户单击该点时,它们会自动重新路由到 Page_2标签?
library(shiny)
library(plotly)
library(tidyverse)
# ui with two panes
# when you click on the outlier in the first plot
# you are routed to the second "point explorer" page
ui <- navbarPage("Plotly On Click Switch Pane",
tabPanel("Page_1",
mainPanel(plotlyOutput("plot"),
tableOutput("text"))),
tabPanel("Page_2",
mainPanel(plotlyOutput("ind_plot"))
))
server <- function(input, output) {
# plot on first page
output$plot <- renderPlotly({
ggplotly(source = "sub_iris",
ggplot(iris, aes(x = Species, y = Petal.Width)) +
geom_boxplot()
)
})
# create reactive for subset plot on second tab
s <- reactive({ event_data("plotly_click", source = "sub_iris") })
# plot text on first page (test)
output$text <- renderTable(event_data("plotly_click", source = "sub_iris"))
# this is the correct plot, but I want to re-route the user here when they click on a point
output$ind_plot <- renderPlotly({
iris_ind <- subset(iris)[subset(s(), curveNumber == 0)$pointNumber + 1,]
ggplotly(
ggplot(iris_ind, aes(x = Species, y = Sepal.Length)) +
geom_bar(stat = "identity")
)
})
}
# Run the application
shinyApp(ui = ui, server = server)
解决方案
您可以updateNavbarPage
在为您navbarPage
提供后使用id
:
library(shiny)
library(plotly)
library(tidyverse)
# ui with two panes
# when you click on the outlier in the first plot
# you are routed to the second "point explorer" page
ui <- navbarPage("Plotly On Click Switch Pane", id = "navbarID",
tabPanel("Page_1",
mainPanel(plotlyOutput("plot"),
tableOutput("text"))),
tabPanel("Page_2",
mainPanel(plotlyOutput("ind_plot"))
))
server <- function(input, output, session) {
# plot on first page
output$plot <- renderPlotly({
ggplotly(source = "sub_iris",
ggplot(iris, aes(x = Species, y = Petal.Width)) +
geom_boxplot()
)
})
# create reactive for subset plot on second tab
s <- reactive({
event_data("plotly_click", source = "sub_iris")
})
observeEvent(s(), {
updateNavbarPage(session, inputId = "navbarID", selected = "Page_2")
})
# plot text on first page (test)
output$text <- renderTable(req(s()))
# this is the correct plot, but I want to re-route the user here when they click on a point
output$ind_plot <- renderPlotly({
req(s())
iris_ind <- subset(iris)[subset(s(), curveNumber == 0)$pointNumber + 1,]
ggplotly(
ggplot(iris_ind, aes(x = Species, y = Sepal.Length)) +
geom_bar(stat = "identity")
)
})
}
# Run the application
shinyApp(ui = ui, server = server)
推荐阅读
- c# - 更新导致数据丢失/删除
- email - google sheet : 以 pdf 格式发送多张带有多个电子邮件地址的表格
- openapi - 如何使用 OpenApi 模式中的 OperationId?
- php - 如何解决“未调度预期的 [App\Events\UserRegistered] 事件。” 错误?
- scala - 有没有办法用每行的自定义连接来连接两个 Spark 数据帧
- python - 如何展开螺旋图?
- scala - 如何在 MacOS 上的 intellij IDEA 中更改运行时 JAVA 堆空间?
- javascript - 无法以 html 形式编写 AJAX 输出变量
- c - 从浮点数中分离数字
- php - 集合无法转换为 int Laravel