Make graphs in Python with NetworkX


In [ ]:
%matplotlib inline

import networkx as nx
import matplotlib.pyplot as plt

Example 1


In [ ]:
g = nx.Graph()

g.add_node("Foo")
g.add_edge("Foo", 1)
g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(1, 4)
g.add_edge(3, 4)

In [ ]:
list(g.nodes())

In [ ]:
list(g.edges())

In [ ]:
pos = nx.spring_layout(g)

nx.draw_networkx(g, pos, node_color='#ffaaff', node_size=800)

#plt.savefig("ex1.png")
plt.show()

Example 2


In [ ]:
g = nx.Graph()
g.add_edges_from([(0, 1), (0, 2), (0, 3), (1, 2)])

In [ ]:
list(g.nodes())

In [ ]:
list(g.edges())

In [ ]:
pos = nx.spring_layout(g)

nx.draw_networkx_nodes(g, pos, node_size=20)
nx.draw_networkx_edges(g, pos, alpha=0.4)

#plt.savefig("ex2.png")
plt.show()

Random graph


In [ ]:
g = nx.gnm_random_graph(10, 20)

In [ ]:
list(g.nodes())

In [ ]:
list(g.edges())

In [ ]:
pos = nx.spring_layout(g)

nx.draw_networkx_nodes(g, pos, node_size=20)
nx.draw_networkx_edges(g, pos, alpha=0.4)
nx.draw_networkx_labels(g, pos, alpha=0.4)

#plt.savefig("random_graph1.png")
plt.show()