NetworkX 绘图10种代码
时间: 2023-12-27 14:03:15 浏览: 156
下面是使用NetworkX绘制常见图形的10种代码:
1. 无向图
```
import networkx as nx
G = nx.Graph()
G.add_edge(1, 2)
G.add_edge(2, 3)
G.add_edge(3, 1)
nx.draw(G, with_labels=True)
```
2. 有向图
```
import networkx as nx
G = nx.DiGraph()
G.add_edge(1, 2)
G.add_edge(2, 3)
G.add_edge(3, 1)
nx.draw(G, with_labels=True)
```
3. 加权图
```
import networkx as nx
G = nx.Graph()
G.add_edge(1, 2, weight=0.5)
G.add_edge(1, 3, weight=0.75)
G.add_edge(2, 3, weight=0.9)
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True)
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
```
4. 大图布局
```
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge(1, 2)
G.add_edge(2, 3)
G.add_edge(3, 1)
pos = nx.spring_layout(G, k=0.5, iterations=50)
nx.draw(G, pos, with_labels=True)
plt.show()
```
5. 圆形布局
```
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge(1, 2)
G.add_edge(2, 3)
G.add_edge(3, 1)
pos = nx.circular_layout(G)
nx.draw(G, pos, with_labels=True)
plt.show()
```
6. 随机布局
```
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge(1, 2)
G.add_edge(2, 3)
G.add_edge(3, 1)
pos = nx.random_layout(G)
nx.draw(G, pos, with_labels=True)
plt.show()
```
7. Shell布局
```
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge(1, 2)
G.add_edge(2, 3)
G.add_edge(3, 1)
pos = nx.shell_layout(G)
nx.draw(G, pos, with_labels=True)
plt.show()
```
8. Spectral布局
```
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge(1, 2)
G.add_edge(2, 3)
G.add_edge(3, 1)
pos = nx.spectral_layout(G)
nx.draw(G, pos, with_labels=True)
plt.show()
```
9. Planar布局
```
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge(1, 2)
G.add_edge(2, 3)
G.add_edge(3, 1)
pos = nx.planar_layout(G)
nx.draw(G, pos, with_labels=True)
plt.show()
```
10. Bipartite Graph布局
```
import networkx as nx
import matplotlib.pyplot as plt
B = nx.Graph()
B.add_nodes_from([1, 2, 3, 4], bipartite=0)
B.add_nodes_from(['a', 'b', 'c'], bipartite=1)
B.add_edges_from([(1, 'a'), (1, 'b'), (2, 'b'), (2, 'c'), (3, 'c'), (4, 'a')])
pos = nx.bipartite_layout(B, [1, 2, 3, 4])
nx.draw(B, pos, with_labels=True)
plt.show()
```
以上是10种常见的使用 NetworkX 绘图的代码示例,可以根据需求选择对应的代码。
阅读全文