Note
Go to the end to download the full example code.
四格图#
使用matplotlib绘制一个4x4的图形。
这个示例展示了如何使用`networkx.draw`的关键字参数来自定义一个包含4x4网格的简单图形的可视化效果。
import matplotlib.pyplot as plt
import networkx as nx
G = nx.grid_2d_graph(4, 4) # 4x4 网格
pos = nx.spring_layout(G, iterations=100, seed=39775)
# 创建一个2x2的子图
fig, all_axes = plt.subplots(2, 2)
ax = all_axes.flat
nx.draw(G, pos, ax=ax[0], font_size=8)
nx.draw(G, pos, ax=ax[1], node_size=0, with_labels=False)
nx.draw(
G,
pos,
ax=ax[2],
node_color="tab:green",
edgecolors="tab:gray", # 节点表面颜色
edge_color="tab:gray", # 图边缘的颜色
node_size=250,
with_labels=False,
width=6,
)
H = G.to_directed()
nx.draw(
H,
pos,
ax=ax[3],
node_color="tab:orange",
node_size=20,
with_labels=False,
arrowsize=10,
width=2,
)
# 设置轴的边距,以确保节点不被裁剪
for a in ax:
a.margins(0.10)
fig.tight_layout()
plt.show()
Total running time of the script: (0 minutes 0.135 seconds)