Attributes such as weights, labels, colors or any other property can be attached to graphs, nodes or edges.
Each graph, node and edge can hold key-value pairs of attributes. By default these are empty. But attributes can be added or changed, using add_edge() and add_node() methods, or directly manipulated.
Graph attributes
Graph attributes can be assigned when creating a new graph.
import networkx as nx
G = nx.Graph(day="Friday")
print(G.graph)
The output looks like this
[(1, 2, {'weight': 4.7, 'color': 'blue'}), (2, 3, {'weight': 8}), (3, 4, {'color': 'red'}), (4, 5, {'color': 'red'})] [(1, 2, {'weight': 4.7, 'color': 'blue'}), (2, 3, {'weight': 8}), (3, 4, {'color': 'red', 'weight': 4.2}), (4, 5, {'color': 'red'})]
We can also modify attributes later.
import networkx as nx
G = nx.Graph(day="Friday")
print(G.graph)
G.graph['day'] = 'Monday'
print(G.graph)
The output looks like this
{'day': 'Friday'}
{'day': 'Monday'}
Node attributes
We can add node attributes using add_node(), add_nodes_from() or nodes.
import networkx as nx
G = nx.Graph()
G.add_node(1, time='5pm')
G.add_nodes_from([3], time='2pm')
print(G.nodes[1])
G.nodes[1]['room'] = 714
print(G.nodes.data())
The output looks like this
{'time': '5pm'} [(1, {'time': '5pm', 'room': 714}), (3, {'time': '2pm'})]
Edge attributes
Similar to node attributes, we can add edge attributes using add_edge(), add_edges_from() and edges.
import networkx as nx
G = nx.Graph()
G.add_edge(1, 2, weight=4.7)
G.add_edges_from([(3, 4), (4, 5)], color='red')
G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})])
print(G.edges.data())
G[1][2]['weight'] = 4.7
G.edges[3, 4]['weight'] = 4.2
print(G.edges.data())
The output looks like this
[(1, 2, {'weight': 4.7, 'color': 'blue'}), (2, 3, {'weight': 8}), (3, 4, {'color': 'red'}), (4, 5, {'color': 'red'})]
[(1, 2, {'weight': 4.7, 'color': 'blue'}), (2, 3, {'weight': 8}), (3, 4, {'color': 'red', 'weight': 4.2}), (4, 5, {'color': 'red'})]
Comments