Python,NetworkX六角形格子问题-如何创建完美的格子? [英] Python, NetworkX hexagonal lattice problem - how to create a perfect lattice?

查看:98
本文介绍了Python,NetworkX六角形格子问题-如何创建完美的格子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我尝试使用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:

with_positions (bool (default: True)) – Store the coordinates of each node in the graph node attribute ‘pos’. The coordinates provide a lattice with vertical columns of hexagons offset to interleave and cover the plane. Periodic positions shift the nodes vertically in a nonlinear way so the edges don’t overlap so much.

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六角形格子问题-如何创建完美的格子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆