evansyangs evansyangs
首页
分类
标签
归档
GitHub (opens new window)

Evan Yang

摸鱼小能手
首页
分类
标签
归档
GitHub (opens new window)
  • NetworkX Learning Notes
  • 1. Creating a graph
  • 2. Nodes
  • 3. Edges
  • 4. What to use as nodes and edges
  • 5. Accessing edges and neighbors
  • 6. Adding attributes to graphs, nodes, and edges
    • 6.1 Graph attributes
    • 6.2 Node attributes
    • 6.3 Edge Attributes
  • 7. Analyzing graphs
  • 8. Directed graphs
  • 9. Drawing graphs
  • 10. Graph generators and graph operations
  • 11. Multigraphs
目录

6. Adding attributes to graphs, nodes, and edges

Attributes such as weights, labels, colors, or whatever Python object you like, can be attached to graphs, nodes, or edges.

Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys must be hashable). By default these are empty, but attributes can be added or changed using add_edge, add_node or direct manipulation of the attribute dictionaries named G.graph, G.nodes, and G.edges for a graph G.

# 6.1 Graph attributes

Assign graph attributes when creating a new graph

G = nx.Graph(day="Friday")
G.graph
1
2

Or you can modify attributes later

G.graph['day'] = "Monday"
G.graph
1
2

# 6.2 Node attributes

Add node attributes using add_node(), add_nodes_from(), or G.nodes

G.add_node(1, time='5pm')
G.add_nodes_from([3], time='2pm')
G.nodes[1]

G.nodes[1]['room'] = 714
G.nodes.data()
1
2
3
4
5
6

提示

Note that adding a node to G.nodes does not add it to the graph, use G.add_node() to add new nodes. Similarly for edges.

# 6.3 Edge Attributes

Add/change edge attributes using add_edge(), add_edges_from(), or subscript notation.

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})])
G[1][2]['weight'] = 4.7
G.edges[3, 4]['weight'] = 4.2
1
2
3
4
5

The special attribute weight should be numeric as it is used by algorithms requiring weighted edges.

编辑 (opens new window)
#Python
上次更新: 2021/02/16, 02:45:37
5. Accessing edges and neighbors
7. Analyzing graphs

← 5. Accessing edges and neighbors 7. Analyzing graphs→

最近更新
01
Dell7472黑苹果
03-27
02
上手HackMD
04-13
03
Windows Terminal设置
03-14
更多文章>
Theme by Vdoing | Copyright © 2019-2023 Evan Yang
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式