Skip to content

Visualization

Use NetworkX together with Matplotlib for simple visualization of networks.

Install

Pip install the libraries

pip install networkx matplotlib

Code

Assume you have solved a model with a graph g. Let's draw a network with labeled vertices and edges with non-zero values.

Consider the code snippet below.

import math
import networkx
import matplotlib
import matplotlib.pyplot as plt

edges = [x.edge for x in g.vars if not math.isclose(x.x, 0, abs_tol=0.001)]
gx = networkx.DiGraph()
gx.add_nodes_from([i for i in range(n)])
gx.add_edges_from(edges)
# pos = {i: (x[i], y[i]) for i in range(n)} # for lists of x,y coordinates
pos = networkx.spring_layout(gx) # alternative layout
networkx.draw_networkx_nodes(gx, pos, nodelist=gx.nodes)
networkx.draw_networkx_labels(gx, pos, labels={i: i for i in gx.nodes})
networkx.draw_networkx_edges(gx, pos, nodelist=gx.edges)
# plt.show() # if gui backend is supported
plt.savefig("mygraph.png")

First the non-zero edges are extracted from the graph, next part builds the network and adds labels, and last the graph is drawn.