In [ ]:
import matplotlib.pyplot as plt
import networkx as nx # for networks
In [ ]:
# initialize the graph/ network
G1 = nx.DiGraph() #directed graph
#add nodes
G1.add_node(1)
G1.add_node(2)
G1.add_node(3)
G1.add_node(4)
G1.add_node(5)
#add edges
G1.add_edge(1, 2) #connection between node 1 and 2
G1.add_edge(1, 3) #connection between node 1 and 3, and so on for the rest
G1.add_edge(1, 4)
G1.add_edge(5, 4)
G1.add_edge(1, 5)
In [ ]:
plt.figure(figsize=(5,5))
pos = nx.spring_layout(G1) #define the position in whch our nodes can be visualized, spring layout is the most common used
nx.draw_networkx_nodes(G1, pos, node_size=500, node_color='#fb8500')
nx.draw_networkx_edges(G1, pos, edge_color='#8338ec', width=2)
nx.draw_networkx_labels(G1, pos, font_color='#ede0d4')
plt.show()
No description has been provided for this image
In [ ]:
#task
#draw a network including 3 nodes(1, 2, b)
#link them so that 1 ->2, 2 ->b, 1->b
G2 = nx.DiGraph()
G2.add_node(1)
G2.add_node(2)
G2.add_node('b')
# add edges with weight
G2.add_edge(1, 2, weight=0.6)
G2.add_edge(2, 'b', weight=1)
G2.add_edge(1, 'b', weight= 0.2)
In [ ]:
#extract the weight in a list
weight_list= list(nx.get_edge_attributes(G2, 'weight').values())
weight_list
Out[ ]:
[0.6, 0.2, 1]
In [ ]:
plt.figure(figsize=(5,5))
pos_G2 = nx.spring_layout(G2)
nx.draw_networkx_nodes(G2, pos_G2, node_size=800, node_color='#8338ec')
nx.draw_networkx_edges(G2, pos_G2, edge_color='#ffbe0b', width=weight_list,
                       min_source_margin=0, min_target_margin=20, connectionstyle='arc3, rad=0.2')
nx.draw_networkx_labels(G2, pos_G2, font_color='#ffbe0b')
plt.show()
No description has been provided for this image
In [ ]: