【问题标题】:Best way to plot a 2D square lattice of atoms in Python?在 Python 中绘制二维原子晶格的最佳方法?
【发布时间】:2020-06-03 17:07:48
【问题描述】:

问题总结: 我正在研究一个物理问题,我想绘制一个二维原子晶格,其中节点已使用箭头连接,如下所示2D lattice figure

我尝试过的: 我尝试使用 NetworkX 的 grid_2d_graph,从 answer 获得帮助,但无法让它按我的意愿工作。我使用的代码如下:

G = nx.grid_2d_graph(4,4)
pos = dict( (n, n) for n in G.nodes() )
nx.draw_networkx(G, pos=pos)
plt.axis('off')
plt.show()

这产生了以下image,这与我的想法并不完全一致。

【问题讨论】:

  • 什么决定了箭头的方向?

标签: python python-3.x networkx physics


【解决方案1】:

这是使用matplotlibarrow 的简单方法。它要求将网格(图形)表示为字典,其中键是网格上的点(节点)坐标,值是应绘制 outgoing 箭头(边)的相邻点.当网格大小发生变化时,您可能需要使用wh 等来控制绘制元素的大小。

grid = {  # point(x, y), outgoing connections [points] 
    (0, 0): [(0, 1), (1, 0)],
    (0, 1): [],
    (1, 0): [],
    (1, 1): [(1, 0), (0, 1)]
}

w = 0.005  # Errorwidth
h = 0.05   # Errorhead width

fig, ax = plt.subplots()
for point, connections in grid.items():
    for outgoing in connections:
        dx = outgoing[0] - point[0]
        dy = outgoing[1] - point[1]
        ax.arrow(point[0], point[1],
                 dx / 2, dy / 2,
                 width=w, head_width=h,
                 facecolor="k",
                 zorder=0)
        ax.arrow(point[0] + dx / 2,
                 point[1] + dy / 2,
                 dx / 2, dy / 2,
                 width=w, head_width=0,
                 facecolor="k",
                 zorder=0)
    ax.plot(*point,
            marker="o", markersize=10, markeredgecolor="k",
            markerfacecolor="red",
            zorder=1)

【讨论】:

  • 哇,谢谢!这太棒了:) 当我得到你的答案时,我也在尝试颤抖情节,所以我将它添加为另一个答案。谢谢!
【解决方案2】:

当我想到 Jan 的答案时,我正试图使用​​颤抖图。我已经修改了他的代码来处理箭袋图

def plot_vector(p1,p2):
    p1 = np.array(p1)
    p2 = np.array(p2)
    dp = p2-p1
    plt.quiver(p1[0], p1[1], dp[0], dp[1],angles='xy', scale_units='xy', scale=1, headwidth = 5, headlength = 7)


grid = {  # point(x, y), outgoing connections [points] 
    (0, 0): [(0, 1), (1, 0)],
    (0, 1): [],
    (1, 0): [],
    (1, 1): [(1, 0), (0, 1)]
}


fig, ax = plt.subplots()
for point, connections in grid.items():
    for outgoing in connections:
        plot_vector(point,outgoing)
    plt.plot(*point,
            marker="o", markersize=10, markeredgecolor="k",
            markerfacecolor="red",
            zorder=1)
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-29
    • 2022-01-16
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 2021-06-16
    相关资源
    最近更新 更多