系列传送门
《networkx库整理》
文章目录
在《networkx库整理》中,大家已经了解到了如何利用networkx库进行绘图等内容。
在本文中,将讲述如何将networkx生成的图进行美化。
1. 加载数据
在画图之前,需要将边、节点等数据加载到图中,在本文中,将利用随机生成的图进行讲解。
引用:https://blog.csdn.net/lucdaopencv/article/details/107150912
-
导入包
import networkx as nx # 导入networkx包 import random # 导入random包 import matplotlib.pyplot as plt # 导入画图工具包
-
新建图
G = nx.Graph() # 建立无向图 H = nx.path_graph(50) # 添加节点,此处设置50个节点 G.add_nodes_from(H) # 添加节点
-
随机概率添加边的函数
def rand_edge(vi, vj, p=0.2): # 默认概率p=0.2 probability = random.random() # 生成随机小数 if probability < p: # 如果小于p G.add_edge(vi, vj) # 连接vi和vj节点
-
添加边
i = 0 while i < 50: j = 0 while j < i: rand_edge(i, j) # 调用rand_edge() j += 1 i += 1
-
显示图
nx.draw(G) plt.show()
-
完整代码
import networkx as nx # 导入networkx包 import random # 导入random包 import matplotlib.pyplot as plt # 导入画图工具包 G = nx.Graph() # 建立无向图 H = nx.path_graph(50) # 添加节点,此处设置50个节点 G.add_nodes_from(H) # 添加节点 def rand_edge(vi, vj, p=0.2): # 默认概率p=0.2 probability = random.random() # 生成随机小数 if probability < p: # 如果小于p G.add_edge(vi, vj) # 连接vi和vj节点 i = 0 while i < 50: j = 0 while j < i: rand_edge(i, j) # 调用rand_edge() j += 1 i += 1 nx.draw(G) plt.show()
-
结果
2. 画图相关函数
2.1 nx.draw()
下面这行代码为nx.draw的部分参数。
nx.draw(G,pos = nx.random_layout(G),node_color = 'b',edge_color = 'r',with_labels = True,font_size =18,node_size =20)
该函数至少接受一个参数:待绘制的网络G
详细参数说明如下表所示:
参数 | 说明 |
---|---|
G | 一个网络Graph |
pos | 布局。可选: circular_layout:节点在一个圆环上均匀分布 random_layout:节点随机分布 shell_layout:节点在同心圆上分布 spring_layout: 用Fruchterman-Reingold算法排列节点(样子类似多中心放射状) spectral_layout:根据图的拉普拉斯特征向量排列节点 |
node_size | 指定节点的尺寸大小(默认是300) |
node_color | 指定节点的颜色(默认是红色,可以用十六进制颜色码,也可以用字符串简单标识颜色,例如’r’或’red’为红色,'y’或’yellow’为黄色) |
node_shape | 节点的形状(默认是圆形,用字符串’o’标识) |
alpha | 透明度(默认是1.0,不透明,0为完全透明) |
width | 边的宽度(默认为1.0) |
edge_color | 边的颜色(默认为黑色) |
style | 边的样式(默认为实线,可选: solid、dashed、dotted、dashdot) |
with_labels | 节点是否带标签(默认为True) |
font_size | 节点标签字体大小(默认为12) |
font_color | 节点标签字体颜色(默认为黑色) |
2.2 nx.draw_networkx_nodes()
nx.draw_networkx_nodes(G, pos, nodelist=None, node_size=300, node_color='r', node_shape='o', alpha=1.0, cmap=None, vmin=None, vmax=None, ax=None, linewidths=None, label=None, **kwds)
参数 | 说明 |
---|---|
G | 图。一个网络Graph |
pos | 字典。以节点作为键、位置作为值的字典。位置应该是长度为2的序列 |
nodelist | 列表,可选。只绘制指定的节点(默认为G.nodes()) |
node_size | 标量或数组。节点的大小(默认值为300)。如果指定了数组,则数组的长度必须与节点列表相同 |
node_color | 颜色字符串或浮点数数组。节点的颜色。可以是单个颜色格式字符串(默认为’ r '),也可以是与nodelist相同长度的颜色序列。如果指定了数值,则使用cmap和vmin、vmax参数将它们映射为颜色 |
node_shape | 字符串。节点的形状。’ so^>v<dph8 ’ 其中之一 (默认= ’ o ') |
alpha | 浮点数。节点透明度(默认=1.0) |
cmap | Matplotlib色图。用于映射节点强度的色图(默认=None) |
vmin | 浮点数。节点颜色映射缩放的最小值(默认=None) |
vmax | 浮点数。节点颜色映射缩放的最大值(默认=None) |
ax | Matplotlib Axes 对象,可选。在指定的Matplotlib轴中绘制图形 |
linewidths | [无|标量|序列]。符号边框的线宽(默认=1.0) |
label | [无|字符串]。图例的标签 |
2.3 nx.draw_networkx_edges()
nx.draw_networkx_edges(G, pos, edgelist=None, width=1.0, edge_color='k', style='solid', alpha=None, edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None, arrows=True, label=None, **kwds)
参数 | 说明 |
---|---|
G | 图。一个网络Graph |
pos | 字典。以节点作为键、位置作为值的字典。位置应该是长度为2的序列 |
edgelist | 边元组的集合。只绘制指定的边(默认=G.edges()) |
width | 浮点数。边的线宽(默认=1.0) |
edge_color | 颜色字符串或浮点数数组。边的颜色。可以是一个单一的颜色格式字符串(默认= ’ r '),或与edgelist相同长度的颜色序列。如果指定了数值,则它们将被映射到edge_cmap和edge_vmin、edge_vmax中的颜色。 |
style | 字符串。边线样式(默认= ’ solid ')(solid|dashed|dotted, dashdot) |
alpha | 浮点数。边透明度(默认=1.0) |
edge_cmap | Matplotlib色图。用于映射边强度的色图(默认=无) |
edge_vmin | 边缘颜色映射缩放的最小值(默认=无) |
edge_vmax | 边缘颜色映射缩放的最大值(默认=无) |
ax | Matplotlib Axes 对象,可选。在指定的Matplotlib轴中绘制图形 |
arrows | 布尔值,可选(默认 = True)。对于有向图,如果为真,则绘制箭头。 |
label | [无|字符串]。图例的标签 |
经过稍微调整 nx.draw() 中的参数,即可美化一开始生成的随机图。
pos = nx.spring_layout(G, iterations=200)
nx.draw(G, pos, node_color=range(50), node_size=500, cmap=plt.cm.Blues, edge_color='#00649a')
plt.show()
3. 网络图示例
来源:https://github.com/networkx/networkx/tree/master/examples/drawing
3.1 Directed Graph
"""
==============
Directed Graph
==============
Draw a graph with directed edges using a colormap and different node sizes.
Edges have different colors and alphas (opacity). Drawn using matplotlib.
"""
import matplotlib as mpl
import matplotlib.pyplot as plt
import networkx as nx
G = nx.generators.directed.random_k_out_graph(10, 3, 0.5)
pos = nx.layout.spring_layout(G)
node_sizes = [3 + 10 * i for i in range(len(G))]
M = G.number_of_edges()
edge_colors = range(2, M + 2)
edge_alphas = [(5 + i) / (M + 4) for i in range(M)]
nodes = nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color="blue")
edges = nx.draw_networkx_edges(
G,
pos,
node_size=node_sizes,
arrowstyle="->",
arrowsize=10,
edge_color=edge_colors,
edge_cmap=plt.cm.Blues,
width=2,
)
# set alpha value for each edge
for i in range(M):
edges[i].set_alpha(edge_alphas[i])
pc = mpl.collections.PatchCollection(edges, cmap=plt.cm.Blues)
pc.set_array(edge_colors)
plt.colorbar(pc)
ax = plt.gca()
ax.set_axis_off()
plt.show()
3.2 Edge Colormap
"""
=============
Edge Colormap
=============
Draw a graph with matplotlib, color edges.
"""
import matplotlib.pyplot as plt
import networkx as nx
G = nx.star_graph(20)
pos = nx.spring_layout(G)
colors = range(20)
options = {
"node_color": "#A0CBE2",
"edge_color": colors,
"width": 4,
"edge_cmap": plt.cm.Blues,
"with_labels": False,
}
nx.draw(G, pos, **options)
plt.show()
3.3 Four Grids
"""
==========
Four Grids
==========
Draw a graph with matplotlib.
"""
import matplotlib.pyplot as plt
import networkx as nx
G = nx.grid_2d_graph(4, 4) # 4x4 grid
pos = nx.spring_layout(G, iterations=100)
plt.subplot(221)
nx.draw(G, pos, font_size=8)
plt.subplot(222)
nx.draw(G, pos, node_color="k", node_size=0, with_labels=False)
plt.subplot(223)
nx.draw(G, pos, node_color="g", node_size=250, with_labels=False, width=6)
plt.subplot(224)
H = G.to_directed()
nx.draw(H, pos, node_color="b", node_size=20, with_labels=False)
plt.show()
3.4 House With Colors
"""
=================
House With Colors
=================
Draw a graph with matplotlib.
"""
import matplotlib.pyplot as plt
import networkx as nx
G = nx.house_graph()
# explicitly set positions
pos = {0: (0, 0), 1: (1, 0), 2: (0, 1), 3: (1, 1), 4: (0.5, 2.0)}
nx.draw_networkx_nodes(G, pos, node_size=2000, nodelist=[4])
nx.draw_networkx_nodes(G, pos, node_size=3000, nodelist=[0, 1, 2, 3], node_color="b")
nx.draw_networkx_edges(G, pos, alpha=0.5, width=6)
plt.axis("off")
plt.show()
3.5 Labels And Colors
"""
=================
Labels And Colors
=================
Draw a graph with matplotlib, color by degree.
"""
import matplotlib.pyplot as plt
import networkx as nx
G = nx.cubical_graph()
pos = nx.spring_layout(G) # positions for all nodes
# nodes
options = {"node_size": 500, "alpha": 0.8}
nx.draw_networkx_nodes(G, pos, nodelist=[0, 1, 2, 3], node_color="r", **options)
nx.draw_networkx_nodes(G, pos, nodelist=[4, 5, 6, 7], node_color="b", **options)
# edges
nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
nx.draw_networkx_edges(
G,
pos,
edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)],
width=8,
alpha=0.5,
edge_color="r",
)
nx.draw_networkx_edges(
G,
pos,
edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
width=8,
alpha=0.5,
edge_color="b",
)
# some math labels
labels = {}
labels[0] = r"$a$"
labels[1] = r"$b$"
labels[2] = r"$c$"
labels[3] = r"$d$"
labels[4] = r"$\alpha$"
labels[5] = r"$\beta$"
labels[6] = r"$\gamma$"
labels[7] = r"$\delta$"
nx.draw_networkx_labels(G, pos, labels, font_size=16)
plt.axis("off")
plt.show()
3.6 Node Colormap
"""
=============
Node Colormap
=============
Draw a graph with matplotlib, color by degree.
"""
import matplotlib.pyplot as plt
import networkx as nx
G = nx.cycle_graph(24)
pos = nx.spring_layout(G, iterations=200)
nx.draw(G, pos, node_color=range(24), node_size=800, cmap=plt.cm.Blues)
plt.show()
3.7 Random Geometric Graph
"""
======================
Random Geometric Graph
======================
Example
"""
import matplotlib.pyplot as plt
import networkx as nx
G = nx.random_geometric_graph(200, 0.125)
# position is stored as node attribute data for random_geometric_graph
pos = nx.get_node_attributes(G, "pos")
# find node near center (0.5,0.5)
dmin = 1
ncenter = 0
for n in pos:
x, y = pos[n]
d = (x - 0.5) ** 2 + (y - 0.5) ** 2
if d < dmin:
ncenter = n
dmin = d
# color by path length from node near center
p = dict(nx.single_source_shortest_path_length(G, ncenter))
plt.figure(figsize=(8, 8))
nx.draw_networkx_edges(G, pos, nodelist=[ncenter], alpha=0.4)
nx.draw_networkx_nodes(
G,
pos,
nodelist=list(p.keys()),
node_size=80,
node_color=list(p.values()),
cmap=plt.cm.Reds_r,
)
plt.xlim(-0.05, 1.05)
plt.ylim(-0.05, 1.05)
plt.axis("off")
plt.show()
3.8 Spectral Embedding
"""
==================
Spectral Embedding
==================
The spectral layout positions the nodes of the graph based on the
eigenvectors of the graph Laplacian $L = D - A$, where $A$ is the
adjacency matrix and $D$ is the degree matrix of the graph.
By default, the spectral layout will embed the graph in two
dimensions (you can embed your graph in other dimensions using the
``dim`` argument to either :func:`~drawing.nx_pylab.draw_spectral` or
:func:`~drawing.layout.spectral_layout`).
When the edges of the graph represent similarity between the incident
nodes, the spectral embedding will place highly similar nodes closer
to one another than nodes which are less similar.
This is particularly striking when you spectrally embed a grid
graph. In the full grid graph, the nodes in the center of the
graph are pulled apart more than nodes on the periphery.
As you remove internal nodes, this effect increases.
"""
import matplotlib.pyplot as plt
import networkx as nx
options = {"node_color": "C0", "node_size": 100}
G = nx.grid_2d_graph(6, 6)
plt.subplot(332)
nx.draw_spectral(G, **options)
G.remove_edge((2, 2), (2, 3))
plt.subplot(334)
nx.draw_spectral(G, **options)
G.remove_edge((3, 2), (3, 3))
plt.subplot(335)
nx.draw_spectral(G, **options)
G.remove_edge((2, 2), (3, 2))
plt.subplot(336)
nx.draw_spectral(G, **options)
G.remove_edge((2, 3), (3, 3))
plt.subplot(337)
nx.draw_spectral(G, **options)
G.remove_edge((1, 2), (1, 3))
plt.subplot(338)
nx.draw_spectral(G, **options)
G.remove_edge((4, 2), (4, 3))
plt.subplot(339)
nx.draw_spectral(G, **options)
plt.show()