networkx画图整理 函数参数

系列传送门
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)
cmapMatplotlib色图。用于映射节点强度的色图(默认=None)
vmin浮点数。节点颜色映射缩放的最小值(默认=None)
vmax浮点数。节点颜色映射缩放的最大值(默认=None)
axMatplotlib 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_cmapMatplotlib色图。用于映射边强度的色图(默认=无)
edge_vmin边缘颜色映射缩放的最小值(默认=无)
edge_vmax边缘颜色映射缩放的最大值(默认=无)
axMatplotlib 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()

daMuBn.png

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()

  • 36
    点赞
  • 211
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python中,可以使用networkx库来进行图的绘制。首先,需要导入相应的库和模块。引用\[1\]和引用\[2\]中的代码展示了两种不同的绘图方法。 引用\[1\]中的代码展示了如何使用networkx库绘制一个环形树状图。首先,需要导入相应的库和模块,然后使用nx.balanced_tree函数创建一个平衡树状图。接下来,使用graphviz_layout函数设置图的布局,并使用nx.draw函数绘制图形。最后,使用plt.show函数显示图形。 引用\[2\]中的代码展示了如何使用networkx库绘制多个图形。首先,需要导入相应的库和模块。然后,使用nx.binomial_graph函数创建一个二项图。接下来,使用graphviz_layout函数设置图的布局,并使用nx.draw函数绘制图形。最后,使用plt.show函数显示图形。 需要注意的是,以上代码中的路径和程序名称可能需要根据实际情况进行修改。 引用\[3\]提供了关于networkx库的一些基本介绍。networkx是一个用Python语言开发的图论与复杂网络建模工具,可以方便地进行复杂网络数据分析、仿真建模等工作。它支持创建简单无向图、有向图和多重图,内置了许多标准的图论算法,功能丰富且简单易用。 综上所述,使用Pythonnetworkx库可以方便地进行图的绘制和分析。 #### 引用[.reference_title] - *1* *2* *3* [python基础 - networkx 绘图总结](https://blog.csdn.net/qq_19446965/article/details/106745837)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值