Python-使用pyplot将2d数组映射到网格吗?

时间:2018-09-29 09:23:44

标签: python matplotlib colors grid mapping

我是pyplot的新手,无法找到将数组映射到彩色网格的适当解决方案。例如,如果我有一个10x10 2d数组和10x10网格:

[[0,0,0,0,0,1,1,1,1,0],
[0,0,0,0,0,1,0,0,1,0],
[0,0,1,0,1,0,1,1,0,0],
[0,0,1,0,0,1,1,0,1,0],
[0,0,1,0,1,0,0,1,1,0],
[1,0,0,1,0,1,0,0,1,0],
[0,1,0,0,0,1,1,1,1,1],
[0,1,0,0,0,0,1,1,1,1],
[1,0,0,0,1,1,1,0,1,0],
[1,1,1,1,0,0,0,1,1,0]]

如果0和1分别是蓝色和红色,则网格应如下所示:

colored grid (I didn't generate this image)

如何使用pyplot做到这一点?

2 个答案:

答案 0 :(得分:2)

您需要的适当功能是pcolor

from matplotlib import pyplot as plt
from matplotlib import colors
cmap = colors.ListedColormap(['Blue','red'])
plt.figure(figsize=(6,6))
plt.pcolor(data[::-1],cmap=cmap,edgecolors='k', linewidths=3)
plt.show()

enter image description here

或者:

cmap = colors.ListedColormap(['Blue','red'])
plt.figure(figsize=(6,6))
plt.pcolor(data[::-1],cmap=cmap,edgecolors='k', linewidths=3)
plt.xticks(np.arange(0.5,10.5,step=1))
plt.yticks(np.arange(0.5,10.5,step=1))
plt.show()

enter image description here

答案 1 :(得分:1)

是的,您可以使用imshow [matplotlib-doc]

data = [
    [0,0,0,0,0,1,1,1,1,0],
    [0,0,0,0,0,1,0,0,1,0],
    [0,0,1,0,1,0,1,1,0,0],
    [0,0,1,0,0,1,1,0,1,0],
    [0,0,1,0,1,0,0,1,1,0],
    [1,0,0,1,0,1,0,0,1,0],
    [0,1,0,0,0,1,1,1,1,1],
    [0,1,0,0,0,0,1,1,1,1],
    [1,0,0,0,1,1,1,0,1,0],
    [1,1,1,1,0,0,0,1,1,0]
]

import matplotlib.pyplot as plt

plt.imshow(data)
plt.show()

因此,您只需将2d列表传递给imshow(),这将生成以下图像:

result of imshow

如文档中所指定,您可以使用另一种颜色图为01使用其他颜色,例如:

plt.imshow(data, cmap=plt.cm.bwr)

将产生相同的数据,但具有蓝白色红色的颜色图:

result of imshow blue-red