How to customize colours and edges assigned to community members in ggraph?

37 views Asked by At

I apologize in advance if this is a basic question or if I format things incorrectly, I'm new to this forum and also still have a lot to learn about R.

I've cobbled together the following code to colour nodes and edges by community membership. Edges connecting nodes across communities are in grey so that it is differentiated from edges connecting two nodes within a community. The part I'm stuck on is just how to customize the colours used to colour the communities.

Working code below without custom colours:

library(ggraph)
library(purrr)
library(igraph)

g <- erdos.renyi.game(100, 350, type = "gnm")

fse = cluster_leading_eigen(g)
V(g)$color <- fse$membership

a1 <- as.data.frame(get.edgelist(g))
E(g)$color <- map2_dbl(a1$V1, a1$V2, ~ {
  ifelse(
    V(g)$color[V(g)[.x]] ==
      V(g)$color[V(g)[.y]],
    V(g)$color[V(g)[.x]],
    9999) 
})

ggraph(g, layout='fr') + 
  geom_edge_link0(aes(filter=color!=9999 ,color=as.factor(color)), width=0.6, alpha=0.35) + 
  geom_edge_link0(aes(filter=color==9999), color='grey', width=0.5, alpha=0.25) + 
  geom_node_point(aes(color=as.factor(color)), size=3, alpha=0.75) + 
  theme_graph(base_family = 'Helvetica')

I have a custom colour palette I would like to use, and have tried assigning that in the line V(g)$color <- fse$membership as something like V(g)$color <- palette_vector[fse$membership], but that seems to break something I don't understand with the map2_dbl function.

Error produced:

Error in `map2_dbl()`:
ℹ In index: 1.
Caused by error:
! Can't coerce from a string to a double.
Run `rlang::last_trace()` to see where the error occurred.
0

There are 0 answers