【问题标题】:drowing a 1d lattice graph in python networkx在 python networkx 中绘制一维点阵图
【发布时间】:2021-12-10 22:28:33
【问题描述】:

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

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
  • 为什么是range (1,n)?如果你创建nx.grid_graph(range(1,1)),它将是一个零节点的空图,在这种情况下average_shortest_path_length是未定义的,当然会出错。
  • 我应该写什么而不是 range()?
  • 您是否生成[1], [1,2], [1,2,3] ... [1,2,3...,n] 作为网格图的维度并计算每个网格图的average_shortest_path_length?
  • 我想将我的节点数设置在范围内(1,N,10)

标签: python graph networkx lattice


【解决方案1】:

根据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()

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

【讨论】:

  • 感谢您完整而出色的回答:)
猜你喜欢
  • 2017-11-25
  • 1970-01-01
  • 2013-10-13
  • 2021-05-03
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
相关资源
最近更新 更多