Note
Go to the end to download the full example code.
自定义节点图标#
使用自定义图标以matplotlib表示节点的示例。
节点图标的图片来自www.materialui.co
import matplotlib.pyplot as plt
import networkx as nx
import PIL
# 图节点的图像URL
icons = {
"router": "icons/router_black_144x144.png",
"switch": "icons/switch_black_144x144.png",
"PC": "icons/computer_black_144x144.png",
}
# 加载图像
images = {k: PIL.Image.open(fname) for k, fname in icons.items()}
# 生成计算机网络图
G = nx.Graph()
G.add_node("router", image=images["router"])
for i in range(1, 4):
G.add_node(f"switch_{i}", image=images["switch"])
for j in range(1, 4):
G.add_node("PC_" + str(i) + "_" + str(j), image=images["PC"])
G.add_edge("router", "switch_1")
G.add_edge("router", "switch_2")
G.add_edge("router", "switch_3")
for u in range(1, 4):
for v in range(1, 4):
G.add_edge("switch_" + str(u), "PC_" + str(u) + "_" + str(v))
# 获取可重复的布局并创建图形
pos = nx.spring_layout(G, seed=1734289230)
fig, ax = plt.subplots()
# 注意:min_source/target_margin 关键字参数仅适用于 FancyArrowPatch 对象。
# 通过设置 `arrows=True` 强制使用 FancyArrowPatch 进行边绘制
# 但通过 `arrowstyle="-"` 来隐藏箭头
nx.draw_networkx_edges(
G,
pos=pos,
ax=ax,
arrows=True,
arrowstyle="-",
min_source_margin=15,
min_target_margin=15,
)
# 将数据坐标(在xlim和ylim之间缩放)转换为显示坐标
tr_figure = ax.transData.transform
# 从显示坐标转换为图形坐标
tr_axes = fig.transFigure.inverted().transform
# 选择图像的大小(相对于X轴)
icon_size = (ax.get_xlim()[1] - ax.get_xlim()[0]) * 0.025
icon_center = icon_size / 2.0
# 为每个节点添加相应的图像
for n in G.nodes:
xf, yf = tr_figure(pos[n])
xa, ya = tr_axes((xf, yf))
# 获取重叠的轴并绘制图标
a = plt.axes([xa - icon_center, ya - icon_center, icon_size, icon_size])
a.imshow(G.nodes[n]["image"])
a.axis("off")
plt.show()
Total running time of the script: (0 minutes 0.098 seconds)