rggplot2ggnetwork

R ggnetwork: unable to change graph layout


I am trying ggnetwork and ggplot2 to plot some graph visualisation but I am unable to change the graph layout parameter that comes with the ggnetwork function. My reproducible code are as follows, and I am running this on R 4.0.3 on Ubuntu

install.packages("WDI") # this is the data source I need for this example
library(WDI)
new_wdi_cache <- WDIcache()
library(igraph)
library(tidyverse)
library(ggnetwork)
        
education<-WDI(indicator=c("SE.PRM.ENRR","SE.SEC.ENRR",
                           "SE.TER.ENRR","SE.SEC.PROG.ZS","SE.PRM.CMPT.ZS"),
               start=2014,
               end=2014,
               extra= TRUE,
               cache=new_wdi_cache)
education<-education[education$region!="Aggregates",]
education<-na.omit(education)

education.features <- education[,4:8]
education.features_scaled <-scale(education.features)
education.distance_matrix <- as.matrix(dist(education.features_scaled))
education.adjacency_matrix <- education.distance_matrix < 1.5

g1<-graph_from_adjacency_matrix(education.adjacency_matrix, mode="undirected")

new.g2<-ggnetwork(g1, layout = "kamadakawai") # LINE A
ggplot(new.g2, aes(x=x, y=y, xend=xend, yend=yend))+
  geom_edges(colour="grey")+geom_nodes(size=5,aes(colour=species ))+
  theme_blank()+labs(caption='WDI School enrollment and progression datasets')

On line A, I get an error that I really cannot understand:

Error: $ operator is invalid for atomic vectors

What does that mean? And if I remove the 'layout=' parameter from ggnetwork, the code runs. However I really need to change the layout.


Solution

  • The layout parameter doesn't take a string, but the output from a igraph::layout_ function.

    So you can do:

    new_g2 <- ggnetwork(g1, layout = igraph::layout.kamada.kawai(g1))
    
    ggplot(new_g2, aes(x, y, xend = xend, yend = yend)) +
      geom_edges(colour = "grey") +
      geom_nodes(size = 8, aes(colour = name)) +
      theme_blank() + 
      labs(caption = 'WDI School enrollment and progression datasets') +
      theme(plot.caption = element_text(size = 16))
    

    enter image description here