问题摘要:我正在做一道物理题,我想绘制一个二维原子格,其中的节点已经用箭头连接起来了,如图所示 二维网格图.
我试过的:我试过使用 网格_2d_graph 从NetworkX公司,借助这个 回答 但没能让它如我所愿。 我使用的代码如下。
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()
这产生了以下结果 形象,这并不是我心中所想的。
下面是一个简单的方法,使用 matplotlib
's arrow
. 它要求网格(图)用一个字典来表示,其中键是网格上的点(节点)坐标,值是相邻的点,其中一个 外发 箭头(边缘)应该被绘制。当你的网格大小发生变化时,你可能会需要玩转 w
, h
等来控制绘制元素的大小。
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)
当我看到Jan的答案时,我正试图使用quiver plots。我修改了他的代码,使之能与quiver plots一起使用。
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()