我创建了一个简单的绘图,当用户单击一个点时,它会在第二个选项卡上生成另一个绘图,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)
您可以在为navbarPage
提供id
后使用updateNavbarPage
:
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)