Update data frame of click data with user input

末鹿安然 提交于 2019-12-07 15:23:27

Take a look at this solution. It probably has still some work do to but it gives you a possible direction. I think that the observer that was reacting to two inputs was not a good solution since a change in any of them would add a row to val$data.

This is the modified code:

    library(shiny)
    library(ggplot2)

    ui <- basicPage(
            plotOutput("plot1", click = "plot_click"),
            radioButtons("cls", "Clasa:", choices = list("Red" = -1, "Blue" = 1), selected = 1), 
            actionButton("updateData", "Update data"),
            actionButton("refreshline", "Rline"),
            verbatimTextOutput("info"),
            verbatimTextOutput("data")
    )

    server <- function(input, output) {

            x1 <- c(3, 10, 15, 3, 4, 7, 1, 12, 8, 18, 20, 4, 4, 5, 10)   #x
            x2 <- c(4, 10, 12, 17, 15, 20, 14, 3, 4, 15, 12, 5, 5, 6, 2) #y
            cls <- c(-1, 1, -1, 1, 1, 1, -1, 1, -1, 1, 1, 1, 1, -1, 1)   #class

            # initialize reactive values with existing data
            val <- reactiveValues( clickx = NULL, clicky = NULL, data = cbind (x1, x2, cls))

            observeEvent(input$updateData, {
                    if (input$updateData > 0) {
                            val$data <- rbind(val$data, cbind(input$plot_click$x, input$plot_click$y, as.numeric(input$cls)))
                    }

            })
            observeEvent(input$plot_click, {
                    val$clickx = c(val$clickx, input$plot_click$x)
                    val$clicky = c(val$clicky, input$plot_click$y)  
            })        

            output$plot1 <- renderPlot({
                    p <- ggplot(data = NULL, aes(x=val$data[,1], y=val$data[,2], color = ifelse(val$data[,3] > 0, "Class 1","Class -1")))
                    p <- p + geom_point()
                    p <- p + xlab("x1")  
                    p <- p + ylab("x2") 
                    p <- p + scale_color_manual(name="Class Labels", values=c('#f8766d','#00BFC4'))
                    p <- p + guides(color = guide_legend(override.aes = list(linetype = 0 )), 
                                    linetype = guide_legend())
                    p <- p + theme_bw() 
                    p

                    if(input$refreshline)
                            p <- p + stat_smooth(method=lm)                         
                    p

            })


            output$info <- renderText({
                    input$plot_click
                    paste0("x = ", val$clickx, ", y = ",val$clicky, "\n")
            })
            output$data <- renderPrint({
                    val$data
            })

    }

    shinyApp(ui, server)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!