我是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分别是蓝色和红色,则网格应如下所示:
如何使用pyplot做到这一点?
答案 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()
或者:
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()
答案 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()
,这将生成以下图像:
如文档中所指定,您可以使用另一种颜色图为0
和1
使用其他颜色,例如:
plt.imshow(data, cmap=plt.cm.bwr)
将产生相同的数据,但具有蓝白色红色的颜色图: