NetworkX 图可视化技巧

February 29, 2024

内置布局

默认布局是弹簧布局(spring layout)。下面是几种常用布局:

networkx_visualization_layout_options0alt

内置布局示例

# libraries
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
 
# Build a dataframe with your connections
df = pd.DataFrame({ 'from':['A', 'B', 'C','A','E','F','E','G','G','D','F'], 'to':['D', 'A', 'E','C','A','F','G','D','B','G','C']})

# Build your graph
G=nx.from_pandas_edgelist(df, 'from', 'to')
 
# Circular
nx.draw(G, with_labels=True, node_size=1500, node_color="skyblue", pos=nx.circular_layout(G))
plt.title("circular")
plt.show()
 
# Spring
nx.draw(G, with_labels=True, node_size=1500, node_color="skyblue", pos=nx.spring_layout(G))
plt.title("spring")
plt.show()

自定义布局

draw 接口

draw(G, pos=None, ax=None, **kwds) 绘制图的简化视图。默认使用整个 Matplotlib 图幅,不显示节点、边或坐标轴的标签。如果需要标题和坐标轴标签等功能,请参阅 draw_networkx()。

参数说明:

G:一个 NetworkX 图。

pos:以节点为键、位置为值的字典。省略时会用弹簧布局计算位置。其他计算节点位置的函数见 networkx.drawing.layout。

ax:在指定的 Matplotlib Axes 上绘图。

kwds:可选关键字参数的说明见 networkx.draw_networkx()。

根据文档可知,在下面的调用中, nx.draw(G, with_labels=True, node_size=1500, node_color="skyblue", pos=nx.spring_layout(G)) nx.spring_layout(G) 会根据图 G 生成位置字典。

  1. 可以编写自己的位置计算函数,让它接收一个 NetworkX 图并返回各节点的位置。

  2. 还可以创建自己的 Matplotlib Axes。下面先说说 Axes 是什么。

Matplotlib 的 Axes 对象

在 Matplotlib 中,一个 Axes 定义了一块可以绘图的区域。 通过 Axes,可以设置这块区域在最终图中的位置、边距以及其他属性。 常见的子图就是一个 Axes。

matplotlib_figure_axes_axis0alt

示例

给 Matplotlib 中的 NetworkX 图留出边距

我想用 Matplotlib 渲染一个 NetworkX 图。节点标签较长,每个大约有 10 到 50 个字符,经常被截断,没法读全。能不能把最终画面稍微“拉远”,把文字都显示出来?

创建一个 Axes 对象并为它设置边距,就解决了这个问题:

ax1 = plt.subplot(111)
ax1.margins(0.3)           

nx.draw(
  G,
  ax=ax1,
  with_labels=True,
  font_size=8,
  node_color='white',
)

参考资料

  1. Mohit Mayank. (Jan 26, 2021). Visualizing Networks in Python [Blog post]. Towards Data Science. Retrieved from https://towardsdatascience.com/visualizing-networks-in-python-d70f4cbeb259

  2. 禹洋搬运工. (Nov 19, 2018). python matplotlib中axes与axis的区别是什么? 1.axes subplot axis 先说第一个疑惑 Axes - Subplot - Axis 之间到底是个什么关系? 因为我是努力在看英文的教程,所以刚开始对axes和axis是基本搞不清的,一个是轴的复数,一个是轴,好像设定图像属性的时候经常用axes,具体到某个坐标轴的时候才会用axis。然后教程还说,subplot和axes基本就是一个意思。真是坑坑坑。。。 扛不住,翻了翻中文教程,好像有的教程就直接把axes翻译成子图了,好像这个世界就压根没有subplot和axes的区别。。看了半天,其实我还是觉得axes翻译成轴域比较贴切,下面就结合后来看到的各种教程来讲讲自己最后的理解。. [Answer]. zhihu. https://www.zhihu.com/question/51745620/answer/231113561

  3. 咕咕小虎. (April 4, 2018). 第一已经回答得很清楚了,我也被这个恶心过,说一种更好理解的方式。可以把fig想象成windows的桌面,你可以有好几个桌面。然后axes就是桌面上的图标,subplot也是图标,他们的区别在:axes是自由摆放的图标,甚至可以相互重叠,而subplot是“自动对齐到网格”。但他们本质上都是图标,也就是说subplot内部其实也是调用的axes,只不过规范了各个axes的排列罢了。. [Answer]. zhihu. https://www.zhihu.com/question/51745620/answer/373278296

  4. Jesse Aldridge. (Mar 29, 2021). Creating an axis and setting a margin on that did the trick: ax1 = plt.subplot(111)ax1.margins(0.3)nx.draw(G,ax=ax1,with_labels=True,font_size=8,node_color='white',). [Answer]. stackoverflow. https://stackoverflow.com/questions/66862622/add-padding-to-networkx-graph-in-matplotlib/66863072#66863072

  5. Version3.2.1>Reference>Drawing>draw (n.d.). networkx documentation. Retrieved April 5, 2024, from https://networkx.org/documentation/stable/reference/generated/networkx.drawing.nx_pylab.draw.html#draw https://networkx.org/documentation/stable/reference/generated/networkx.drawing.nx_pylab.draw.html#draw

  6. v3.8.4-2-g4dcfcf8b7b>API Reference>matplotlib.pyplot>matplotlib.pyplot.subplot(n.d.). matplotlib documentation. Retrieved April 5, 2024, from https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplot.html#matplotlib-pyplot-subplot

  7. Network Layout Possibilities(n.d.). python graph gallery. Retrieved April 5, 2024, from https://python-graph-gallery.com/322-network-layout-possibilities/

© 2024 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2024-02-29). NetworkX 图可视化技巧. https://caiborui.com/blog/2024-02-29-en-networkx-graph-visualization-tips-zhtrans

@misc{borui2024-bbcc6cd1,
  author = {borui},
  title = {{NetworkX 图可视化技巧}},
  year = {2024},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2024-02-29-en-networkx-graph-visualization-tips-zhtrans}
}