I want to add/merge two graphs in form of adjacency matrices and take care of the structure.
The first graph looks like this:
The related adjacency matrix is:
0. 1. 1. 1.
1. 0. 1. 1.
1. 1. 0. 1.
1. 1. 1. 0.
The second graph looks like this:
The related adjacency matrix is:
[[0. 1. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[1. 0. 1. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 1. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[1. 0. 0. 0. 0. 1. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 1. 0. 1. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 1. 0. 1. 0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 1. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 1. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 1. 0. 1. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 1. 0. 0. 1. 0. 1. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 1. 0. 0. 0. 0. 1.]
[0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 1. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 1. 0. 1.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 1. 0.]]
Now I thought, I can pad the first matrix and simply add the first matrix to the second. But the result is not what i desired.
So my question is, how can I merge/add two adjacency matrices and taking care/maintain of their structure ... ?
My desired outcome should look like this:
Any idea would be helpful :).
I think this is the sort of thing you might be after. The trick is to use nx.compose
to merge the two graphs together.
Set up first graph:
import networkx as nx
adjmat1 = np.array([[0., 1., 1., 1.],
[1., 0., 1., 1.],
[1., 1., 0., 1.],
[1., 1., 1., 0.]])
adjmat1_df = pd.DataFrame(adjmat1)
node_labels = [(1,1),(1,2),(2,1),(2,2)]
adjmat1_df.columns = node_labels
adjmat1_df.index = node_labels
G1 = nx.from_pandas_adjacency(adjmat1_df)
pos = {(x,y):(y,-x) for x,y in G1.nodes()}
nx.draw(G1, pos=pos,
node_color='lightgreen',
with_labels=True,
node_size=600)
Set up second graph (I've gone for a quick grid setup but you can use your second adjacency matrix to create a graph as in the first step):
# Following @yatu's SO answer for plotting https://stackoverflow.com/a/62161953/6386471
G2 = nx.grid_2d_graph(4,4)
plt.figure(figsize=(4,4))
pos = {(x,y):(y,-x) for x,y in G2.nodes()}
nx.draw(G2, pos=pos,
node_color='lightgreen',
with_labels=True,
node_size=600)
Use nx.compose
to combine the graphs:
H = nx.compose(G1,G2)
pos = {(x,y):(y,-x) for x,y in H.nodes()}
nx.draw(H, pos=pos,
node_color='lightgreen',
with_labels=True,
node_size=600)