在Python中绘制二维方形原子晶格的最佳方法?

2024-04-20 14:25:32 发布

您现在位置:Python中文网/ 问答频道 /正文

问题摘要: 我正在研究一个物理问题,我想画一个二维原子晶格,其中的节点用箭头连接,如图所示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,这与我的想法不完全一致


Tags: answerposnetworkx节点方式物理plt箭头
2条回答

这里是一个使用matplotlibarrow的简单方法。它要求将网格(图形)表示为字典,其中键是网格上的点(节点)坐标,值是应绘制输出箭头(边)的相邻点。当网格大小更改时,您可能需要使用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)

enter image description here

当我想到简的答案时,我正试图使用箭袋图。我修改了他的代码来处理箭袋图

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

Resultant Plot

相关问题 更多 >