thomasp85/ggraph

Feature request: small multiples plots replicating entire network

alexpghayes opened this issue · 1 comments

I'd like to be able to replicate the entire network (all nodes and all edges) so that I can visualize multiple node-level features on the network all at once. Here's a hacky attempt to do this with patchwork -- I would much prefer to do this via some sort of build-in facetting if possible.

library(ggraph)
#> Loading required package: ggplot2
library(tidygraph)
#> 
#> Attaching package: 'tidygraph'
#> The following object is masked from 'package:stats':
#> 
#>     filter
library(patchwork)
library(tidyr)

gr <- as_tbl_graph(highschool) |>
  mutate(
    feat1 = sample(LETTERS[1:3], n(), replace = TRUE),
    feat2 = sample(LETTERS[1:8], n(), replace = TRUE)
  ) |>
  mutate_at(vars(feat1, feat2), as.factor)

p1 <- ggraph(gr) +
  geom_edge_link(alpha = 0.1) +
  geom_node_point(aes(color = feat1)) +
  scale_color_brewer(type = "qual") +
  theme_graph()
#> Using "stress" as default layout

p2 <- ggraph(gr) +
  geom_edge_link(alpha = 0.1) +
  geom_node_point(aes(color = feat2)) +
  scale_color_brewer(type = "qual") +
  theme_graph()
#> Using "stress" as default layout

p1 + p2
#> Warning: Using the `size` aesthetic in this geom was deprecated in ggplot2 3.4.0.
#> ℹ Please use `linewidth` in the `default_aes` field and elsewhere instead.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
#> generated.

Created on 2023-05-05 with reprex v2.0.2

See some more discussion at: https://stackoverflow.com/questions/75598414/small-multiples-plots-replicating-entire-network-in-each-panel-in-ggraph

I second what hsa been said on stackoverflow. I dont think that your approach is hacky. Here it is wrapped in an lapply for any number of features.

library(ggraph)
#> Loading required package: ggplot2
library(tidygraph)
#> 
#> Attaching package: 'tidygraph'
#> The following object is masked from 'package:stats':
#> 
#>     filter
library(patchwork)
library(tidyr)

gr <- as_tbl_graph(highschool) |>
  mutate(
    feat1 = sample(LETTERS[1:3], n(), replace = TRUE),
    feat2 = sample(LETTERS[1:8], n(), replace = TRUE),
    feat3 = sample(LETTERS[1:5], n(), replace = TRUE),
    feat4 = sample(LETTERS[1:2], n(), replace = TRUE),
  ) |>
  mutate_at(vars(feat1, feat2, feat3, feat4), as.factor)

plist <- lapply(c("feat1", "feat2", "feat3", "feat4"), function(x) {
  feat <- ensym(x)
  ggraph(gr, "stress") +
    geom_edge_link(alpha = 0.1) +
    geom_node_point(aes(color = !!feat)) +
    scale_color_brewer(type = "qual") +
    theme_graph()
})

wrap_plots(plist, ncol = 2)
#> Warning: Using the `size` aesthetic in this geom was deprecated in ggplot2 3.4.0.
#> ℹ Please use `linewidth` in the `default_aes` field and elsewhere instead.

Created on 2023-06-13 with reprex v2.0.2