Drawing grids and graphs with Networkx

I want to draw a square grid with Networkx . I did something like this:

 import matplotlib.pyplot as plt import numpy as np import networkx as nx L=4 G = nx.Graph() pos={} for i in np.arange(L*L): pos[i] = (i/L,i%L) nx.draw_networkx_nodes(G,pos,node_size=50,node_color='k') plt.show() 

However, the conclusion is just an empty figure. How to resolve this?

In addition, I would like to join the points horizontally and vertically with arrows. The direction of the arrows going from (i,j) to (i+1,j) should depend on the sign of the element i, j of the matrix A , which I already have. How to do it?

+6
source share
1 answer

This is the explicit graph constructor for this nx.grid_2d_graph :

 G = nx.grid_2d_graph(L,L) nx.draw(G,node_size=2000) plt.show() 

enter image description here

We can modify this undirected graph into a directed graph that meets your boundary criteria. As an example, I removed the edges pointing from the origin. You can tailor this solution to your needs:

 G2 = nx.DiGraph(G) for edge in G2.edges(): if edge != tuple(sorted(edge)): G2.remove_edge(*edge) nx.draw_spectral(G2,node_size=600,node_color='w') 

enter image description here

+8
source

Source: https://habr.com/ru/post/950892/


All Articles