Using linked brushing within a ggraph network chart


#1

Hello,

I’m trying to use the brushedPoints() function within a shiny app so that users can select specific points in a network chart rendered via the ggraph package and it will return the names of those specific points. In the code below, I’ve put together a small app to exemplify my attempt.

library(ggraph)
library(igraph)
library(shiny)

ui <- fluidPage(
    plotOutput("plot", brush = brushOpts(id = "plot_brush"))
)

server <- function(input, output) {
  graph <- graph_from_data_frame(highschool)

  output$plot <- renderPlot({
    ggraph(graph) + 
      geom_edge_link(aes(colour = factor(year))) + 
      geom_node_point()
  })

  observe(print(
    brushedPoints(as_data_frame(graph, what = "vertices"), input$plot_brush)
        )
    )
}

shinyApp(ui, server)

When running this app, my attempt is to select an area in the chart, and the console would return the names of the points selected. However, as is the code is not returning anything. Is there another way to achieve this? Is this possible at all with a ggraph network chart?


#2

I think I’ve figured it out once I’ve learned of the existence of ggplot_build():

library(ggraph)
library(igraph)
library(shiny)
library(dplyr)

ui <- fluidPage(
  plotOutput("plot", brush = brushOpts(id = "plot_brush"))
)

server <- function(input, output) {
  graph2 <- graph_from_data_frame(highschool)

  set.seed(2017)
  p <- ggraph(graph2, layout = "nicely") + 
    geom_edge_link() + 
    geom_node_point()

  plot_df <- ggplot_build(p)

  coords <- plot_df$data[[2]]

  output$plot <- renderPlot(p)

  coords_filt <- reactive({
    if (is.null(input$plot_brush$xmin)){
      coords
    } else {
    filter(coords, x >= input$plot_brush$xmin, 
           x <= input$plot_brush$xmax, 
           y >= input$plot_brush$ymin, 
           y <= input$plot_brush$ymax)
    }
  })

  observe(print(
    coords_filt()
  )
  )

}

shinyApp(ui, server)