在 python networkx 中绘制一维点阵图

drowing a 1d lattice graph in python networkx

我想绘制一维点阵图,但我面临以下问题:

NetworkXPointlessConcept:空图没有路径,因此没有平均最短路径长度 这段代码有什么问题? 谢谢。

N = 1000
x = 0
for n in range(1, N, 10):
    lattice_1d_distance = list()
    d = 0
    lattice_1d = nx.grid_graph(range(1,n))
    
    d = nx.average_shortest_path_length(lattice_1d)
    lattice_1d_distance.append(d)
    x.append(n)
plt.plot(x, lattice_1d_distance)  
plt.show()

根据 networkx 文档 nx.grid_graph 输入是 nx.grid_graph

的维度列表

例子

print(list(range(1,4)))
nx.draw(nx.grid_graph(list(range(1,4))) # this is a two dimensional graph, as there is only 3 entries AND ONE ENTRY = 1

[1, 2, 3]

print(list(range(1,5)))
nx.draw(nx.grid_graph([1,2,3,4])) # this is a 3 dimensional graph, as there is only 4 entries AND ONE ENTRY = 1

[1, 2, 3, 4]

因此,假设您想要 1. 绘制网格图的距离与维数增量的关系,但每个维的大小为常数,或者您想要 2. 绘制网格图每个维度的 距离与大小增量的关系 ,但具有常数 维度数 :

import networkx as nx
import matplotlib.pyplot as plt

N = 10
x = []
lattice_1d_distance = []
for n in range(1, 10):
    d = 0
    lattice_1d = nx.grid_graph([2]*n) # plotting incrementing number of dimensions, but each dimension have same length.
    d = nx.average_shortest_path_length(lattice_1d)
    lattice_1d_distance.append(d)
    x.append(n)
plt.plot(x, lattice_1d_distance)  
plt.show()

N = 10
x = []
lattice_1d_distance = []
for n in range(1, 10):
    d = 0
    lattice_1d = nx.grid_graph([n,n]) # plotting 2 dimensional graphs, but each graph have incrementing length for each dimension.
    d = nx.average_shortest_path_length(lattice_1d)
    lattice_1d_distance.append(d)
    x.append(n)
plt.plot(x, lattice_1d_distance)  
plt.show()

另外,需要注意列表变量的声明。