问题
I have a very simple Shiny
app as below -
library(shiny)
ui <- fluidPage(
div(id = "01", style = "cursor:pointer; height: 300px; width: 300px; text-align: center; background-color: green", HTML("01")),
div(id = "02", style = "cursor:pointer; height: 300px; width: 300px; text-align: center; background-color: blue", HTML("02")),
div(id = "03", style = "cursor:pointer; height: 300px; width: 300px; text-align: center; background-color: red", HTML("03")),
plotOutput("plot")
)
shinyApp(ui, server = function(input, output) { })
}
Within this framework, I want to achieve a clickable event over the three divs
wherein click on first div
would generate a cdf plot of Normal distribution
, 2nd div
would generate t distribution
and 3rd one would generate a GED distribution
.
I can use a drop-down box
etc. to achieve the same, alternatively, I may also use 3 different plotOutput()
for each div. However in my present case I have too many such divs
which therefore would not be feasible to have so many individual plotOutput()
. So I desire to have such functionality through individual divs
with one output.
Is there any way to achieve the same in Shiny
? Any pointer will be highly appreciated.
回答1:
As per @bretauv shinyjs
has onclick
function, so you an do the following, note that you have to provide the plots with distributions I am simply doing the changes with the normal
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs(), # Set up shinyjs
column(3,
div(id = "01", style = "cursor:pointer; height: 300px; width: 300px; text-align: center; background-color: green", HTML("01")),
div(id = "02", style = "cursor:pointer; height: 300px; width: 300px; text-align: center; background-color: blue", HTML("02")),
div(id = "03", style = "cursor:pointer; height: 300px; width: 300px; text-align: center; background-color: red", HTML("03")),
),
column(9,
plotOutput("plot")
)
)
v <- reactiveValues()
normal <- function(v){
v$x <- seq(-10, 10, by = .1)
v$y <- rnorm(v$x)
v$title <- "Normal distribution"
}
tdistr <- function(v){
v$x <- seq(-10, 10, by = .1)
v$y <- rnorm(v$x)
v$title <- "T-distribution"
}
geddistr <- function(v){
v$x <- seq(-10, 10, by = .1)
v$y <- rnorm(v$x)
v$title <- "GED distribution"
}
server = function(input, output,session) {
observe({
onclick("01",normal(v))
onclick("02",tdistr(v))
onclick("03",geddistr(v))
})
output$plot <- renderPlot({
req(v$x)
plot(v$x,v$y,main = v$title)
})
}
shinyApp(ui, server)
来源:https://stackoverflow.com/questions/60752449/generate-different-clickable-events-on-divs-in-shiny-app