问题描述
因此,我尝试使用Python中的NetworkX生成六边形格子.使用代码后:
G = nx.hexagonal_lattice_graph(m = 2,n = 2,周期性= False,with_positions = True,create_using = None)plt.subplot(111)nx.draw(G,with_labels = True,font_weight ='bold')plt.show()
我得到一个看起来像这样的六边形格子:
So I am trying to generate a hexagonal lattice using NetworkX in Python. After using code:
G = nx.hexagonal_lattice_graph(m=2, n=2, periodic=False, with_positions=True, create_using=None)
plt.subplot(111)
nx.draw(G, with_labels=True, font_weight='bold')
plt.show()
I am getting a hexagonal lattice which looks like this:lattice
As you can see, this lattice is formed from irregular hexagons and everytime the code is ran the shape changes. Is there a way to generate a perfect hexagonal lattice using NetworkX, i.e this, but with only X number of hexagons?
Thanks!
You need to use the with_postion
attribute in the hexagonal_lattic_graph
function and set it to True
. This will store the positions of the nodes in an attribute called pos
inside the Graph G
itself. You can read more about from the documentation here:
So, you just need to extract the positions from the graph itself, like this:
pos = nx.get_node_attributes(G, 'pos')
Then, pass this with pos
while drawing your graph
import networkx as nx
import matplotlib.pyplot as plt
# create the graph and set with_positions=True
G = nx.hexagonal_lattice_graph(m=2, n=2, periodic=False, with_positions=True, create_using=None)
plt.subplot(111)
# Extract the positions
pos = nx.get_node_attributes(G, 'pos')
# Pass the positions while drawing
nx.draw(G, pos=pos, with_labels=True, font_weight='bold')
plt.show()
这篇关于Python,NetworkX六角形格子问题-如何创建完美的格子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!