This is question relates to my previous questions on this topic:
- Summing Nodes in a Network
- Coloring Nodes on a Graph
I have this network graph of 1000 nodes:
library(igraph)
width <- 30
height <- 20
num_nodes <- width * height
# Create a grid
x <- rep(1:width, each = height)
y <- rep(1:height, times = width)
g <- make_empty_graph(n = num_nodes, directed = FALSE)
# Function to get node index
get_node_index <- function(i, j) (i - 1) * height + j
# Add edges
edges <- c()
for(i in 1:width) {
for(j in 1:height) {
current_node <- get_node_index(i, j)
# Connect to right neighbor
if(i < width) edges <- c(edges, current_node, get_node_index(i + 1, j))
# Connect to bottom neighbor
if(j < height) edges <- c(edges, current_node, get_node_index(i, j + 1))
}
}
g <- add_edges(g, edges)
V(g)$x <- x
V(g)$y <- y
par(mfrow=c(1,1))
V(g)$name <- 1:num_nodes
plot(g, vertex.size = 7, vertex.label = V(g)$name, vertex.label.cex = 0.6, main = "Map with Node Indices")
Goal: I want to split this network into 4 mini squares of equal size
I thought of the following strategy:
- Find out the corners of the original network. These will be nodes with only 2 connections each
- Take each corner, and keep selecting its neighbors, the neighbor’s neighbors etc etc
- Repeat for all corners
I tried to implement this as follows:
First I defined a function that extracts nodes and neighbors based on 4 boundaries:
get_node_index <- function(i, j) (i - 1) * height + j
select_square_nodes <- function(g, x_start, x_end, y_start, y_end) {
nodes <- c()
for (i in x_start:x_end) {
for (j in y_start:y_end) {
nodes <- c(nodes, get_node_index(i, j))
}
}
return(nodes)
}
The next part took me a while to figure out – I needed to define these boundaries relative to the dimensions of the original network:
square1 <- select_square_nodes(g, 1, width/2, 1, height/2)
square2 <- select_square_nodes(g, (width/2) + 1, width, 1, height/2)
square3 <- select_square_nodes(g, 1, width/2, (height/2) + 1, height)
square4 <- select_square_nodes(g, (width/2) + 1, width, (height/2) + 1, height)
Finally, I put all the networks into a list and then wrote a quick function to plot these mini networks:
selected_nodes_list <- list(square1, square2, square3, square4)
plot_subgraph <- function(g, nodes, title) {
subg <- induced_subgraph(g, nodes)
plot(subg,
main = title,
vertex.size = 10,
vertex.label = V(subg)$name,
vertex.label.cex = 0.6)
}
par(mfrow = c(2, 2), mar = c(1, 1, 3, 1))
for (i in 1:length(selected_nodes_list)) {
plot_subgraph(g, selected_nodes_list[[i]], paste("Subgraph", i))
}
Currently I am manually comparing each mini network to the original network to confirm that the connections in the original network are preserved in the mini networks. Can someone help me understand if I have done this correctly?
farrow90 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.