[英]Resetting plotly event_data upon radio button select in shiny
我有一個交互顯示的閃亮文本,它捕獲了一個繪圖中的單擊事件。 如果未單擊任何內容,則顯示默認文本,單擊某點后,將顯示其相應的值。
但是,我也有一個單選按鈕,可以選擇圖中所示的內容。 問題是,當我更改選定的單選按鈕時,交互式顯示的文本不再正確,因為繪圖發生了變化,並且無法捕獲,這在下面的簡化示例中可以看到。 因此,每當我在單選按鈕中選擇其他選項時,我都希望將event_data重置(並因此顯示默認文本)。
我知道有多種方法可以創建單獨的“重置”按鈕(例如,使用shinyjs
包,請參見此處 ),但我想知道是否可以通過某種方式將此重置功能耦合到單選按鈕。
library(ggplot2)
library(shiny)
library(shinydashboard)
library(plotly)
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(
fluidRow(
box(plotlyOutput("first"),
radioButtons("radbut", "Choose:", c("Sepal" = "sepal","Petal" =
"petal"))
),
box(textOutput("second"))
)
)
)
server <- function(input, output, session) {
output$first <- renderPlotly({
if (input$radbut == "sepal") {
gp <- ggplot(data = iris, aes(x = Sepal.Width, y = Sepal.Length)) +
geom_point()
} else {
gp <- ggplot(data = iris, aes(x = Petal.Width, y = Petal.Length)) +
geom_point()
}
ggplotly(gp, source = "select")
})
output$second <- renderText({
clicked <- event_data("plotly_click", source = "select")
if (is.null(clicked)) {
text = "Select a value"
} else {
text = paste("You clicked:", input$radbut,
clicked[[3]],",", clicked[[4]], sep = " ")
}
text
})
}
shinyApp(ui, server)
這是使用電抗值的可能解決方案(解決方法)。 我認為我必須有一個更優雅的解決方法,但找不到它。
希望這可以幫助!
library(ggplot2)
library(shiny)
library(shinydashboard)
library(plotly)
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(
fluidRow(
box(plotlyOutput("first"),
radioButtons("radbut", "Choose:", c("Sepal" = "sepal","Petal" =
"petal"))
),
box(textOutput("second"))
)
)
)
server <- function(input, output, session) {
defaults <- reactiveValues(part = "Sepal", text = "")
output$first <- renderPlotly({
defaults$text = "Select a value"
if (input$radbut == "sepal") {
defaults$part = "Sepal"
gp <- ggplot(data = iris, aes(x = Sepal.Width, y = Sepal.Length)) +
geom_point()
} else {
defaults$part = "Petal"
gp <- ggplot(data = iris, aes(x = Petal.Width, y = Petal.Length)) +
geom_point()
}
ggplotly(gp, source = "select")
})
clicked <- reactive({
event_data("plotly_click", source = "select")
})
observeEvent(clicked(), {
defaults$text = paste("You clicked:", defaults$part,
clicked()[[3]],",", clicked()[[4]], sep = " ")
})
output$second <- renderText({
defaults$text
})
}
shinyApp(ui, server)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.