Generate, fill and plot a hexagonal lattice in Python

后端 未结 1 1333
伪装坚强ぢ
伪装坚强ぢ 2021-02-10 01:25

I\'d like to modify a Python script of mine operating on a square lattice (it\'s an agent based model for biology), to work in a hexagonal universe.

This is how I create

相关标签:
1条回答
  • 2021-02-10 02:13

    I agree that trying to shoehorn a hexagonal lattice into a cubic is problematic. My suggestion is to use a general scheme - represent the neighboring sites as a graph. This works very well with pythons dictionary object and it trivial to implement the "axial coordinate scheme" in one of the links you provided. Here is an example that creates and draws the "lattice" using networkx.

    import networkx as nx
    G = nx.Graph(directed=False)
    G.add_node((0,0))
    
    for n in xrange(4):
        for (q,r) in G.nodes(): 
            G.add_edge((q,r),(q,r-1))
            G.add_edge((q,r),(q-1,r))
            G.add_edge((q,r),(q-1,r+1))
            G.add_edge((q,r),(q,r+1))
            G.add_edge((q,r),(q+1,r-1))
            G.add_edge((q,r),(q+1,r))
    
    pos = nx.graphviz_layout(G,prog="neato")
    nx.draw(G,pos,alpha=.75)
    
    import pylab as plt
    plt.axis('equal')
    plt.show()
    

    enter image description here

    This is isn't the most optimal implementation but it can generate arbitrarily large lattices:

    enter image description here

    0 讨论(0)
提交回复
热议问题