I have a simple Python and Networkx code that plots a 2D graph along with the node label numbers and edges (edges are irrelevant in my case, so it would be nice if I can somehow remove them):
import matplotlib.pyplot as plt
import pandas as pd
import networkx as nx
csv_io = pd.read_csv('matrix101.csv', index_col=[0])
#csv_list = csv_io.values.tolist()
N = 5
G = nx.grid_2d_graph(N,N)
pos = dict( (n, n) for n in G.nodes() )
labels = dict( ((i, j), i + 1 + (N-1-j) * N ) for i, j in G.nodes() )
nx.draw_networkx(G, pos=pos, labels=labels, node_color='red')
plt.axis('off')
plt.show()
The output is (with node colour red):
I wish to retrieve the node numbers from the 2D graph and compare them to values in a CSV matrix which is similar but slightly modified... for example, with the following 'X' patterns (let's call it "matrix101.csv" from the code above):
1 2 3 4 5
X 7 8 9 10
X 12 13 14 15
16 17 X 19 20
21 22 X 24 25
So basically, when I input the CSV file "matrix101.csv" into the code, the CSV node values must be compared and the values with 'X' should indicate a different colour in the original 2D graph... that is, like a mismatch:
I use Pandas to read the CSV file but that's about it and I've hit a roadblock and unable to proceed further.
Any ideas on how I can realize this idea of comparing both matrices?
Thanks in advance!
P.S. Code snippet borrowed from this question:
Remove rotation effect when drawing a square grid of MxM nodes in networkx using grid_2d_graph
You can try to create color list that you then pass to node_color=
parameter:
import matplotlib.pyplot as plt
import networkx as nx
import pandas as pd
df = pd.read_csv("matrix101.csv", index_col=None, header=None, sep=r"\s+", dtype=str)
N = 5
G = nx.grid_2d_graph(N, N)
pos = dict((n, n) for n in G.nodes())
colors = [
"red" if df.loc[N - 1 - j, i] == str(i + 1 + (N - 1 - j) * N) else "green"
for i, j in G.nodes()
]
# OR:
# colors = ["red" if df.loc[N - 1 - j, i] != "X" else "green" for i, j in G.nodes()]
labels = dict(((i, j), i + 1 + (N - 1 - j) * N) for i, j in G.nodes())
nx.draw_networkx(G, pos=pos, labels=labels, node_color=colors)
plt.axis("off")
plt.show()
Shows: