Search code examples
pythongridpositionnetworkxcartesian-coordinates

Python: reflect positions in a 2D grid graph


In a 2D graph with 10x10 nodes, I realized I want the nodes to be labelled starting from the upper left corner, downwards and column-wise:

1st column -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2nd column -> [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

and so forth until I reach the 10th column. Instead, the code I have labels them starting from the lower left corner, upwards and column-wise. I guess the caveat is in the pos2 line but I don't know how to change it. I've tried to reverse the inds and vals lists but the result was a reflection of the graph with respect to the y or vertical axis. Instead, I am looking for a reflection with respect to the horizontal axis.

import networkx as nx
from pylab import *
import matplotlib.pyplot as plt
%pylab inline

#n=100 Number of nodes
ncols=10 #Number of columns in a 10x10 grid of positions

N=10 #Nodes per side
G=nx.grid_2d_graph(N,N)
labels = dict( ((i,j), i + (N-1-j) * N ) for i, j in G.nodes() )
nx.relabel_nodes(G,labels,False)
inds=labels.keys()
vals=labels.values()
inds=sorted(inds,reverse=False)
vals=sorted(vals, reverse=False)
pos2=dict(zip(vals,inds))
nx.draw_networkx(G, pos=pos2, with_labels=True, node_size = 250, node_color='lightblue')
plt.axis('off')
plt.show()

enter image description here


Solution

  • You could just change the labels when you draw the graph like this

    import networkx as nx                                                                                                                        
    import matplotlib.pyplot as plt                                                 
    
    #n=100 Number of nodes                                                          
    ncols=10 #Number of columns in a 10x10 grid of positions                        
    
    N=10 #Nodes per side                                                            
    G=nx.grid_2d_graph(N,N)                                                         
    pos = dict(zip(G.nodes(),G.nodes()))                                            
    ordering = [(y,N-1-x) for y in range(N) for x in range(N)]                      
    labels = dict(zip(ordering, range(len(ordering))))                              
    nx.draw_networkx(G, pos=pos, with_labels=False, node_size = 250, node_color='lightblue')                                                                       
    nx.draw_networkx_labels(G, pos=pos, labels=labels)                              
    plt.axis('off')                                                                 
    plt.show()