R ggplot2单击boxplot

Joh*_*ohn 5 r ggplot2 shiny

当我单击图表中的一个点时,该点将突出显示为红色.

但很快它又回到了黑色.

有没有办法保持选择?

library(shiny)
library(ggplot2)


server <- function(input, session, output) {
  mtcars$cyl = as.character(mtcars$cyl)


  D = reactive({
    nearPoints(mtcars, input$click_1,allRows = TRUE)
  })

  output$plot_1 = renderPlot({
    set.seed(123)
    ggplot(D(),aes(x=cyl,y=mpg)) + 
      geom_boxplot(outlier.shape = NA) + 
      geom_jitter(aes(color=selected_),width=0.02,size=4)+
      scale_color_manual(values = c("black","red"),guide=FALSE)

  })

  output$info = renderPrint({
    D()
  })
}

ui <- fluidPage(

  plotOutput("plot_1",click = clickOpts("click_1")),
  verbatimTextOutput("info")

)

shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)

Val*_*vić 1

我不确定问题是什么,但这是我想到的第一个解决方法:

            library(shiny)
            library(ggplot2)


            server <- function(input, session, output) {
                    mtcars$cyl = as.character(mtcars$cyl)
                    df <- reactiveValues(dfClikced = mtcars)


                    observe({                
                            if (!is.null(input$click_1)) {
                                    df$dfClikced <- nearPoints(mtcars, input$click_1, allRows = TRUE)        
                            }})

                    output$plot_1 = renderPlot({
                            set.seed(123)
                            if (names(df$dfClikced)[NCOL(df$dfClikced)]== "selected_") {

                                    ggplot(df$dfClikced,aes(x=cyl,y=mpg)) + 
                                            geom_boxplot(outlier.shape = NA) + 
                                            geom_jitter(aes(color=selected_),width=0.02,size=4)+
                                            scale_color_manual(values = c("black","red"),guide=FALSE)       
                            } else {
                                    ggplot(df$dfClikced,aes(x=cyl,y=mpg)) + 
                                            geom_boxplot(outlier.shape = NA) + 
                                            geom_jitter(width=0.02,size=4)+
                                            scale_color_manual(values = c("black","red"),guide=FALSE)         
                            } 

                    })

                    output$info = renderPrint({
                            df$dfClikced
                    })
            }

            ui <- fluidPage(

                    plotOutput("plot_1",click = clickOpts("click_1")),
                    verbatimTextOutput("info")

            )

            shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)

让我知道...