# install.packages("igraph") library(igraph) # Empty graph g <- make_empty_graph(directed=FALSE) # # Add vertices # g <- g %>% add_vertices(1, color="#a3b8a3", size=50) g <- g %>% add_vertices(1, color = "#d7c668", size=50) g <- g %>% add_vertices(10, color = "#cccccc", size=20) plot(g) # # Add edges (to connect vertices) # # Connect the two first vertices g <- g %>% add_edges(c(1,2), weight=0.01, color="#cccccc") plot(g) # Connect 8 to 10 and 7 g <- g %>% add_edges(c(8,10, 8,7), weight=0.01, color="#cccccc") plot(g) # Connect 3, 4, and 5 to 1 g <- g %>% add_edges(c(3,1, 4,1, 5,1), weight=0.01, color="#cccccc") plot(g) # Connect 11 and 12 to 2 with more weight g <- g %>% add_edges(c(12,2, 11,2), weight=1, color="#cccccc") plot(g) # Layouts par(mfrow=c(2,2), mar=c(2,0,4,0)) plot(g, vertex.label=NA, layout=layout_with_fr, main="Force-directed") plot(g, vertex.label=NA, layout=layout_on_grid, main="Grid") plot(g, vertex.label=NA, layout=layout_in_circle, main="Circle") plot(g, vertex.label=NA, layout=layout_nicely, main="Nicely") # # Example with more data: Job Switching Network # # Load data occs <- read.csv("data/occ_codes.tsv", sep="\t") occverts <- read.csv("data/occverts.csv") occlinks <- read.csv("data/occlinks.csv") occgrps <- unique(occverts$grp) head(occverts) head(occlinks) # Subsetting and weights occlinks$relwt <- occlinks$value / max(occlinks$value) occlinks_sub <- occlinks[occlinks$relwt >= .01,] occverts_sub <- occverts[occverts$id %in% occlinks_sub$source | occverts$id %in% occlinks_sub$target,] # Vertices colors occverts_sub$color <- colors()[match(occverts_sub$grp, occgrps)*2] # Form the graph g <- make_empty_graph(directed=FALSE) g <- g %>% add_vertices(dim(occverts_sub)[1], color=occverts_sub$color, size=sqrt(occverts_sub$nwt)/10) %>% set_vertex_attr("occid", value = occverts_sub$id) %>% set_vertex_attr("grp", value = occverts_sub$grp) # Get id of added vertices occverts_sub$vid <- match(occverts_sub$id, V(g)$occid) occverts_sub$name <- occs$name[match(occverts_sub$id, occs$code)] g <- g %>% set_vertex_attr("name", value = occverts_sub$name) # Join ids occlinks_sub$vid_source <- occverts_sub$vid[match(occlinks_sub$source, occverts_sub$id)] occlinks_sub$vid_target <- occverts_sub$vid[match(occlinks_sub$target, occverts_sub$id)] # Add edges for (i in 1:dim(occlinks_sub)[1]) { g <- g %>% add_edges(c(occlinks_sub$vid_source[i], occlinks_sub$vid_target[i]), weight=occlinks_sub$relwt[i]*20, color="#f0f0f0") } # Plot plot(g, vertex.label = NA)