在R的igraph中,如何用邻接矩阵创建带指定节点坐标的图?
No problem at all! The trick here is to first create your graph from the adjacency matrix, then attach your custom coordinates as vertex attributes, and finally use those attributes to define the plot layout. Here's a step-by-step implementation:
Step 1: Build your adjacency matrix
First, create the adjacency matrix that matches your original edge list (a-b, b-c, c-d, undirected):
library('igraph') # Define nodes and adjacency matrix nodes <- c('a','b','c','d') adj_matrix <- matrix(0, nrow = length(nodes), ncol = length(nodes), dimnames = list(nodes, nodes)) # Add edges (undirected, so set both i,j and j,i to 1) adj_matrix['a', 'b'] <- 1 adj_matrix['b', 'a'] <- 1 adj_matrix['b', 'c'] <- 1 adj_matrix['c', 'b'] <- 1 adj_matrix['c', 'd'] <- 1 adj_matrix['d', 'c'] <- 1
Step 2: Create the graph and attach coordinate attributes
Next, generate the graph from the adjacency matrix, then assign your x/y coordinates as vertex attributes:
# Create graph from adjacency matrix g <- graph_from_adjacency_matrix(adj_matrix, mode = "undirected") # Assign custom coordinates to vertex attributes x <- c(0,1,2,3) y <- c(0,1,2,3) V(g)$x <- x V(g)$y <- y
Step 3: Plot with custom layout
When plotting, use the layout parameter to pass your custom coordinates directly:
# Plot the graph using the custom coordinates plot(g, layout = cbind(V(g)$x, V(g)$y))
Full Combined Code
Here's the complete code in one block for convenience:
library('igraph') # Define nodes and adjacency matrix nodes <- c('a','b','c','d') adj_matrix <- matrix(0, nrow = length(nodes), ncol = length(nodes), dimnames = list(nodes, nodes)) # Add undirected edges adj_matrix['a', 'b'] <- adj_matrix['b', 'a'] <- 1 adj_matrix['b', 'c'] <- adj_matrix['c', 'b'] <- 1 adj_matrix['c', 'd'] <- adj_matrix['d', 'c'] <- 1 # Create graph and assign coordinates g <- graph_from_adjacency_matrix(adj_matrix, mode = "undirected") V(g)$x <- c(0,1,2,3) V(g)$y <- c(0,1,2,3) # Plot with custom layout plot(g, layout = cbind(V(g)$x, V(g)$y))
This will produce exactly the same graph as your original code, but using an adjacency matrix instead of an edge list. The key is that we're manually attaching the coordinate attributes to the graph's vertices, then using those attributes to define the plot layout explicitly.
内容的提问来源于stack exchange,提问作者Andry

