将不同值的矩阵可视化为python中的颜色

问题描述 投票:0回答:2

我只想将具有三个不同值(例如0,1和2)的矩阵打印为不同的颜色。假设我有以下网格

import numpy as np
grid=np.zeros((5, 5))
grid[1][1]=2
grid[3][8]=2
grid[3][4]=1
grid[6][7]=1
grid[7][7]=1

如何以一种类似于木板的方式将其可视化,并用一种​​颜色突出显示我的值为“ 1”的位置,而用另一种颜色突出我具有的值为“ 2”的位置。

我尝试过

import matplotlib.pyplot as plt
ax=plt.subplots
ax.imshow(grid)

但是我收到错误消息“'tuple'对象没有属性'imshow'”

感谢您的帮助!

python matplotlib matrix heatmap
2个回答
0
投票

这对我有用:

grid=np.zeros((9, 9))
grid[1][1]=2
grid[3][8]=2
grid[3][4]=1
grid[6][7]=1
grid[7][7]=1

plt.imshow(grid)

enter image description here

注意,在您的示例中,您试图将元素设置在定义的数组之外。所以我将定义扩展为(9,9)


0
投票

尝试一下:

import matplotlib.pyplot as plt
_, ax = plt.subplots(1)
ax.imshow(grid)
© www.soinside.com 2019 - 2024. All rights reserved.