I would like to create an interactive plot with shiny
and ggplot2
. I have been able to do this successfully with geom_point
and other geoms
with an obvious x
and y
axis. When using something like a geom_bar
, though, this is harder since you don't have a y
variable.
There is a solution here and here to extract the x
variable from the click event to do the filtering desired but neither of these handle plots with facets. I would like to use the click option on a ggplot
with facets. I tried to adapt the code at the first link, but this hasn't been successful.
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)
A click on any of the bars does well to filter to the x
values but includes results from all facets. I would like to only include results from the clicked facet.
I have tried using nearPoints
with pannelvar1
but it throws an error since I don't have a y
variable to pass to it.
Any thoughts?
I changed your last function and got the result I think you want.
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, ]
})
I am not sure what error you were getting from trying to access panelvar1, but I used the configuration option options(shiny.trace=TRUE)
to check out how to access the panel variable (log message added below). Perhaps you were just trying to pull the value from the wrong position
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}}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.