John John - 27 days ago 8
R Question

R Shiny : Strange behavior of the brush functionality with ggplot2

Please run the sample code.

When I select points in the scatter plots, those selected points will be deleted from the charts. It's mostly working fine except that, when I select some points close to the corners of the charts, these points will come back after a quick double-self-updating.

For the points residing in the middle part of the charts, it's just working fine.

enter image description here

How to explain this strange behavior?

library(ggplot2)
library(shiny)

server <- function(input, output) {

vals = reactiveValues(keeprows = TRUE)

observeEvent(input$brush_1,{
cat("---------------\n")
print("brush_1")
Res = brushedPoints(mtcars,brush = input$brush_1,allRows = TRUE)
vals$keeprows = !Res$selected_
})

observeEvent(input$brush_2,{
cat("---------------\n")
print("brush_2")
Res = brushedPoints(mtcars,brush = input$brush_2,allRows = TRUE)
vals$keeprows = !Res$selected_
})

D = reactive({
print("D")
mtcars[vals$keeprows,]
})

output$p1 = renderPlot({
print("plot_1")
X = D()
ggplot(X,aes(x=mpg,y=cyl))+geom_point()
})
output$p2 = renderPlot({
print("plot_2")

ggplot(D(),aes(x=mpg,y=wt))+geom_point()
})

output$L = renderPrint({
Res = brushedPoints(mtcars,brush = input$brush_1,allRows = TRUE)
Res
})
}


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


shinyApp(ui = ui, server = server)


It seems that the
brush_1
event is triggered twice and the plot is reset when those strange points are selected.

Answer

The problem happens when you deselect the points at the limits of the plot, because it is then redrawn to fit the whole space, and this unsets the brush...

you can set fix limits on the plot to prevent it:

ggplot(X,aes(x=mpg,y=cyl))+
geom_point()+
scale_x_continuous(limits=c(min(mtcars$mpg),max(mtcars$mpg)))+
scale_y_continuous(limits=c(min(mtcars$cyl),max(mtcars$cyl)))
Comments