要使用 networkx 绘制网格和图形,我们可以采取以下步骤 -
导入 networkx 和 pyplot。
设置图形大小并调整子图之间和周围的填充。
使用nx.grid_2d_graph(3, 3)得到一个二维网格图。网格图的每个节点都连接到其四个最近的邻居。
用 Matplotlib 绘制图形 G。
要显示图形,请使用show()方法。
# Import networkx and pyplot import networkx as nx from matplotlib import pyplot as plt # Set the figure size plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True # Draw the graph G = nx.grid_2d_graph(3, 3) nx.draw(G, node_size=100) plt.show()输出结果
它将产生以下输出