无法使用matplotlib绘制图形

时间:2018-10-04 14:45:32

标签: python matplotlib

我一直试图在网格上找到最短距离的两点。我有2个问题:

1)我无法提出一种有效的算法来找到两点之间的路径。

2)我正在处理4个不同的要点。 0是起点,1表示障碍物,2 s是终点,3表示所访问的点。我希望所访问的地点变成红色。但是当我这样做时,超过一半的图表会变成红色。

这是我的代码:

import matplotlib as mpl
from matplotlib import pyplot
import numpy as np


grid = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [1,0,1,0,1,0,1,0,1,2,1,0,1,0,1,0,1,0,1,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],
    ]





def search(x, y):
    if grid[x][y] == 2:
        print ('found at %d,%d' % (x, y))
        return True
    elif grid[x][y] == 1:
        #print ('wall at %d,%d' % (x, y))
        return False
    elif grid[x][y] == 3:
        print ('visited at %d,%d' % (x, y))
        return False

    #print ('visiting %d,%d' % (x, y))

    # mark as visited
    grid[x][y] = 3

    # explore neighbors clockwise starting by the one on the right
    if ((x < len(grid)-1 and search(x+1, y))
        or (y > 0 and search(x, y-1))
        or (x > 0 and search(x-1, y))
        or (y < len(grid)-1 and search(x, y+1))):
        return True

    return False

search(0, 0)

zvals = grid

ax = pyplot.gca()
major_ticks = np.arange(0.5, 20, 1)
pyplot.xticks(rotation=90)
ax.set_xticks(major_ticks)
ax.set_yticks(major_ticks)
ax.grid(which='both')
pyplot.grid(True)

# make a color map of fixed colors
cmap = mpl.colors.ListedColormap(['white','black'])
bounds=[-2,-1,1,2]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

# tell imshow about color map so that only set colors are used
img = pyplot.imshow(zvals,interpolation='nearest',
                    cmap = cmap,norm=norm)

# make a color bar
pyplot.colorbar(img,cmap=cmap,
                norm=norm,boundaries=bounds,ticks=[0,1])

pyplot.show()

1 个答案:

答案 0 :(得分:1)

由于算法本身运行良好,所以我认为唯一的问题是显示结果的正确性。我建议在网格上使用尽可能多的不同颜色,这里是4种不同的颜色。

GC_PAN_WITH_GUTTER

enter image description here