John John - 2 months ago 14
R Question

R Shiny, how to stop ggplot boxplots from updating themselves as in a group of linked boxplots

When I create a group of linked boxplots( selecting points in one boxplot highlights the corresponding points in all boxplots), the boxplots keep updating themselves for a uncertain amount of times (sometimes only once but sometimes up to 20 times).

Please run the following sample code.

I believe the source of problem is the geom_jitter(). Is there any way to stop the boxplots from updating themselves? Thanks.

library(shiny)
library(ggplot2)

server <- function(input, session, output) {

X = data.frame(x1 = rnorm(1000),
x2 = rnorm(1000),
week = sample(LETTERS[1:10],1000,replace = TRUE)
)

D = reactive({
brushedPoints(X,input$brush_1, allRows = TRUE)
})

output$p1 = renderPlot({
set.seed(123)
ggplot(D(),aes(x=week,y=x1))+
geom_boxplot() +
geom_jitter(aes(color=selected_))+
scale_color_manual(values = c("black","red"),guide=FALSE)


})

output$p2 = renderPlot({
set.seed(123)
ggplot(D(),aes(x=week,y=x2))+
geom_boxplot() +
geom_jitter(aes(color=selected_))+
scale_color_manual(values = c("black","red"),guide=FALSE)

})

}

ui <- fluidPage(
splitLayout(
plotOutput("p1",brush = "brush_1"),
plotOutput("p2",brush = "brush_1")
)
)

shinyApp(ui = ui, server = server)





Update: 2016-9-16

I tried replacing
geom_jitter
with
geom_point
, but the charts still keep updating themselves.

So
geom_jitter
may not be the suspect.

So what is the source of problem on earth?

Answer
library(shiny)
library(ggplot2)

server <- function(input, session, output) {

  X = data.frame(x1 = rnorm(1000),
                 x2 = rnorm(1000),
                 week = sample(LETTERS[1:10],1000,replace = TRUE)
  )

  vals <- reactiveValues(
    keeprows = rep(TRUE,nrow(X))

  )

  D = reactive({
    R=cbind(X,vals$keeprows)
    #print(sum(R[,"vals$keeprows"]==TRUE))
    R
    })

  output$p1 = renderPlot({
    set.seed(123)
      ggplot(D(),aes(x=week,y=x1))+
      geom_boxplot() +
      geom_jitter(aes(colour=vals$keeprows))+
      scale_color_manual(values = c("black","red"),guide=FALSE)


  })

  output$p2 = renderPlot({
    set.seed(123)

    ggplot(D(),aes(x=week,y=x2))+
    geom_boxplot() +
    geom_jitter(aes(color=vals$keeprows))+
    scale_color_manual(values = c("black","red"),guide=FALSE)

  })

  observeEvent(input$brush_1,{
    Res=brushedPoints(X,input$brush_1,allRows = TRUE)
    vals$keeprows = Res$selected_

  })

  observeEvent(input$brush_2,{
    Res=brushedPoints(X,input$brush_2,allRows = TRUE)
    vals$keeprows = Res$selected_

  })

  observeEvent(input$exclude_reset,{
    vals$keeprows = rep(TRUE,nrow(X))

  })

}

ui <- fluidPage(
  actionButton("exclude_reset","Reset"),
  splitLayout(
    plotOutput("p1",brush = brushOpts("brush_1",resetOnNew = TRUE)),
    plotOutput("p2",brush = brushOpts("brush_2",resetOnNew = TRUE))
  )
)

shinyApp(ui = ui, server = server)
Comments