gpt4 book ai didi

python - Matplotlib 绘制二维网格中环绕边缘的路径

转载 作者:太空宇宙 更新时间:2023-11-03 14:19:51 25 4
gpt4 key购买 nike

我有一个 2D 32 x 32 环形网格世界。 Ant 可以环游世界,当到达一个边缘时, Ant 会绕到世界的另一边。当我使用 Matplotlib 绘制这条路径时:

path = [(0, 1), (0, 2), (0, 3), (31, 3), (31, 2), (31, 1), (0, 1), (0, 2),\
(31, 2), (30, 2), (30, 3), (30, 4), (30, 5), (29, 5)]
ys_path, xs_path = np.array(path).T
axes.plot(xs_path, ys_path, '-')

每当 Ant 绕到另一边时,我都会得到水平和垂直的线。知道我如何无法通过世界中间连接这些点吗?图中,红色圆圈就是 Ant 经过的所有方格。

如果连续之间的差的绝对值为31,则在该位置插入(np.nan, np.nan)......但我不知道该怎么做。

self.path excerpt:
array([[ 0, 1],
[ 0, 1],
[ 31, 0], # at this point in path insert a np.nan tuple
[ 0, -1],
[ 0, -1],
[-31, 0],
[ 0, 1],
[ 31, 0],
[ -1, 0],
[ 0, 1],
[ 0, 1],
[ 0, 1],
[ -1, 0]])

path = np.array(self.path, dtype=np.float)
path = np.insert(path,
np.nonzero(np.abs(np.diff(path, axis=0)) > 1)[0] + 1, np.nan, axis=0)

ys_path, xs_path = np.array(path).T #flip i and j for coordinate system
axes.plot(xs_path+0.5, ys_path+0.5, '-') # centre in middle of square

这实现了我们想要的功能,它在路径数组中插入了一个 NaN 元组,天才!

最佳答案

您似乎正在寻找 np.insert 。它完全符合您的要求。您可以获得 diff 所在位置的索引使用 np.nonzero 返回 +/-1 以外的值。第一个返回值将是行索引,无论中断发生在哪个方向。 diff 中的索引必须递增 1,因为 insert 的操作假设您在之后指定索引插入点:

path = np.array([(0, 1), (0, 2), (0, 3), (31, 3), (31, 2), (31, 1), (0, 1), (0, 2),
(31, 2), (30, 2), (30, 3), (30, 4), (30, 5), (29, 5)], dtype=np.float)
delta = np.diff(path, axis=0)
mask = (np.abs(delta) > 1)
row_indices = np.nonzero(mask)[0]
row_indices += 1
path = np.insert(path, row_indices, np.nan, axis=0)

...

axes.plot(*path.T, '-')

此代码为每个步骤保存一个临时变量,以便更容易理解。当然,您可以根据您的需要和审美偏好将其变成单行或介于两者之间的内容:

path = np.array([(0, 1), (0, 2), (0, 3), (31, 3), (31, 2), (31, 1), (0, 1), (0, 2),
(31, 2), (30, 2), (30, 3), (30, 4), (30, 5), (29, 5)], dtype=np.float)
path = np.insert(path, np.nonzero(np.abs(np.diff(path, axis=0)) > 1)[0] + 1, np.nan, axis=0)

...

axes.plot(*path.T, '-')

根据您稍后计划如何使用 path,可能根本不需要将其拆分并永久转置。您可以使用参数扩展将其作为两个单独的数组传递给axes.plot。

关于python - Matplotlib 绘制二维网格中环绕边缘的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48011070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com