Hi,
I try to get a overlay from some points presented by ggplot in a shiny app with a polygon based on user clicks. So the user can select subpopulations from the xy data for further analysis.
when xy points are clicked interactively I get an error:
"data" must be a data frame, or other object coercible by "fortify()", not an S3 object with class reactivevalues.
I think the problem is that I do not correctly address the values from "gate1".
I have replicated this problem in a small example from the mtcars dataset (see below).
I would appreciate any help,
thanks Alex
library(ggplot2)
ui <- fluidPage(# Some custom CSS for a smaller font for preformatted text
tags$head(tags$style(
HTML("
pre, table.table {
font-size: smaller;
}
")
)),
fluidRow(column(width = 4, wellPanel(
radioButtons("plot_type", "Plot type",
c("base", "ggplot2"))
)),
column(
width = 4,
# In a plotOutput, passing values for click, dblclick, hover, or brush
# will enable those interactions.
plotOutput(
"plot1",
height = 350,
# Equivalent to: click = clickOpts(id = "plot_click")
click = "plot_click",
dblclick = dblclickOpts(id = "plot_dblclick"),
hover = hoverOpts(id = "plot_hover"),
brush = brushOpts(id = "plot_brush")
)
)))
server <- function(input, output) {
gate1 <- reactiveValues(x = NULL, y = NULL)
observeEvent(input$plot_click, {
# Initially will be empty
if (is.null(input$plot_click)) {
return()
}
gate1$x <- c(gate1$x, input$plot_click$x)
gate1$y <- c(gate1$y, input$plot_click$y)
})
output$plot1 <- renderPlot({
gplot <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
if (length(gate1$x > 3))
{
gate <- isolate(gate1)
gplot <-
gplot + geom_polygon(data = gate, aes(fill = "green"))
}
return(gplot)
})
}
shinyApp(ui, server)```